ARTICLE AD BOX
I was experimenting with TypeScript abstract classes and came up with behaviour I cannot figure out and find an explanation (at least the one I would understand).
Suppose we have an abstract class with two properties: both are initialized in the abstract class' constructor, but one is initialized directly in the constructor and the other one is assigned from an abstract method.
We write another class that extends our abstract class and add two subclass properties: one is initialized in the subclass' constructor and the other one in the implemented abstract method.
While in the implemented abstract method, the subclass property seems to be initialized. But afterwards, it is undefined. And I cannot figure out why it is so.
The code:
abstract class ATest { protected readonly absCons: number; protected readonly absFunc: number; constructor(id: number) { this.absCons = id; this.absFunc = this.init(); } protected abstract init(): number; } class Test extends ATest { private readonly extCons: number; private extFunc!: number; // Property in question. constructor(id: number) { super(id); this.extCons = 7777; } protected init(): number { console.log('In init()'); this.extFunc = 2222; const tmp = 4444; console.log('absCons =', this.absCons); console.log('absFunc =', tmp, '(tmp)'); console.log('extCons =', this.extCons); console.log('extFunc =', this.extFunc, '<<<<<<<<<<<<<<<'); console.log('Leaving init()\n'); return tmp; } public check(): void { console.log('In check()'); console.log('absCons =', this.absCons); console.log('absFunc =', this.absFunc); console.log('extCons =', this.extCons); console.log('extFunc =', this.extFunc, '<<<<<<<<<<<<<<<'); console.log('Leaving check()\n'); } } const t = new Test(1111); t.check();The output:
In init() absCons = 1111 absFunc = 4444 (tmp) extCons = undefined extFunc = 2222 <<<<<<<<<<<<<<< Leaving init() In check() absCons = 1111 absFunc = 4444 extCons = 7777 extFunc = undefined <<<<<<<<<<<<<<< Leaving check()Why does it work that way? Is it possible to initialize a subclass property in an abstract method?
