Description
TypeScript currently sets default class param values at the end of the constructor if that constructor doesn't already set a value. In fact, it's smart enough that if the constructor calls another function that sets the value, the default won't be set. Unfortunately, I've found a scenario involving inheritance where I set a value during construction, and then the default class param value stomps it:
- Child class constructor is called.
- Child class calls super's constructor.
- Super class constructor calls a method which the child class overrides, thus calling back into child class' code.
- This child method sets a parameter value.
- -- constructor code finishes --
- TypeScript erroneously sets the default for the child's parameter, stomping on the value set in 4.
I'm not fully aware of the implications, but it seems to me as if default class param values should be set every time (instead of conditionally), and they should be set at the beginning of the constructor before any constructor code or calls to super execute. Either this, or the check to set the default parameter needs to be smarter to detect this case.
TypeScript Version: 2.2.1 / nightly (2.2.0-dev.201xxxxx)
Code
class Foo {
constructor(myVal: number) {
this._setMyVal(myVal);
}
protected _setMyVal(myVal: number) {
// The subclass overrides this method.
}
}
class Bar extends Foo {
private _myVal = 123;
constructor(myVal: number) {
super(myVal);
}
protected _setMyVal(myVal: number) {
this._myVal = myVal;
}
public log() {
console.log(this._myVal);
}
}
const test = new Bar(9);
test.log(); // 123
Expected behavior:
Purely from how I read the code above, given how other languages work, I would expect the final value of _myVal to be 9. Regardless of its default, I set a value during construction and that value shouldn't get reset later.
Actual behavior:
As per the example, TypeScript compiles this to execute this._myVal = 123;
after all constructor code is finished, thus stomping any values set during construction.