CodexBloom - Programming Q&A Platform

TypeScript Class Property implementation patterns as Expected in Child Classes - How to implement?

👀 Views: 1871 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-25
typescript class inheritance TypeScript

I'm not sure how to approach I'm writing unit tests and I'm converting an old project and I'm writing unit tests and I'm working with an scenario with TypeScript where I have a base class with a property that I expect to be initialized in child classes, but I'm getting `undefined` when I try to access it... Here's a simplified version of my code: ```typescript class BaseClass { protected property: string; constructor() { this.property = 'Base'; } } class ChildClass extends BaseClass { constructor() { super(); this.property = 'Child'; } } const child = new ChildClass(); console.log(child.property); // Output: undefined ``` I've confirmed that the constructor of the `ChildClass` is being called, but for some reason, `this.property` is still not set correctly. If I remove the `protected` modifier from `property`, the output becomes 'Child' as expected. This makes me think there's an scenario with accessing the property from a child class when it's protected. I also tried adding an initialization block directly in `ChildClass` like this: ```typescript class ChildClass extends BaseClass { property = 'Child'; // Attempt to initialize property directly constructor() { super(); } } ``` but this results in the same scenario. I looked through the TypeScript documentation and couldn't find anything that explains this behavior. Am I missing something in terms of TypeScript's handling of visibility modifiers or how properties are initialized? Any guidance on how to ensure the property is initialized correctly would be greatly appreciated. The stack includes Typescript and several other technologies. What's the correct way to implement this? Any help would be greatly appreciated! Could this be a known issue? This issue appeared after updating to Typescript LTS. Is there a simpler solution I'm overlooking?