Unable to access extended properties in constructor · Issue #1617 · microsoft/TypeScript (original) (raw)
I'm not sure if this is an intention of typescript or not but acts differently to how I would've expected.
If i have a base class and extend it, overriding some base class properties, then want to work with the properties in the child class constructor I still access the parent properties.
This is shown in the below basic example.
class Base {
public myVar:string = 'Base';
public constructor() {
console.log(this.myVar);
}
}
class Child extends Base {
public myVar:string = 'Child';
}
var base:Base = new Base(); // 'Base' - As expected var child:Child = new Child(); // 'Base' - I would've expected this to be 'Child'
console.log(base.myVar); // 'Base' - As expected console.log(child.myVar); // 'Child' - As expected
This happens in the compiled JS because the super is called before the child properties are set:
function Child() { _super.apply(this, arguments); this.myVar = 'Child'; }
Is this intended? An issue? Or a trade off because of JS limitations? Thanks!
Note that if I do something like this, it works as I would've expected. However it feels like a bit of a hacky work around.
class Base {
public myVar:string = 'Base';
public constructor() {
this.setup();
}
protected setup() {
console.log(this.myVar);
}
}
class Child extends Base {
public myVar:string = 'Child';
public constructor() {
super();
this.setup();
}
}
var base:Base = new Base(); // 'Base' var child:Child = new Child(); // 'Child' - Now as expected
console.log(base.myVar); // 'Base' console.log(child.myVar); // 'Child'