CodexBloom - Programming Q&A Platform

TypeScript Class Initialization Order Causing Undefined Properties in Subclass

👀 Views: 91 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-21
typescript classes inheritance TypeScript

I'm stuck on something that should probably be simple. I just started working with I've tried everything I can think of but Quick question that's been bugging me - I am working with an scenario with class instantiation in TypeScript where properties initialized in the constructor of a parent class are undefined when accessed in a subclass constructor. I have the following setup: ```typescript class Parent { protected value: string; constructor(value: string) { this.value = value; console.log(`Parent initialized with value: ${this.value}`); } } class Child extends Parent { private childValue: string; constructor(value: string, childValue: string) { super(value); this.childValue = childValue; console.log(`Child initialized with childValue: ${this.childValue} and parent value: ${this.value}`); } } const childInstance = new Child('Hello', 'World'); ``` The console output shows `Parent initialized with value: Hello` but when I try to access `this.value` in the `Child` class constructor, I get `undefined` for it, leading to: ``` Child initialized with childValue: World and parent value: undefined ``` I have tried making `value` public instead of protected and ensuring that I'm calling `super(value)` before using `this.value` in the `Child` constructor, but the scenario continues. I don't see any circular references or asynchronous operations that could be affecting this. Could this be related to how TypeScript handles initialization of inherited properties? Any insights or best practices to ensure the properties are correctly initialized would be greatly appreciated! I recently upgraded to Typescript 3.11. I'm coming from a different tech stack and learning Typescript. I'd really appreciate any guidance on this. Thanks for your help in advance!