CodexBloom - Programming Q&A Platform

implementing Constructor Overriding in TypeScript - Incorrect Property Initialization

👀 Views: 42 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
typescript oop inheritance TypeScript

I'm stuck trying to Quick question that's been bugging me - I'm working with an scenario with constructor overriding in TypeScript that I need to seem to resolve. I have a base class `Animal` and a derived class `Dog`. The `Animal` class has a property `species` which I want to initialize differently in the `Dog` class, but I'm seeing unexpected behavior where the `species` property is either not set correctly or showing up as `undefined` when I instantiate `Dog`. Here's the relevant code snippet: ```typescript class Animal { species: string; constructor(species: string) { this.species = species; } } class Dog extends Animal { constructor() { super('Dog'); // I expect species to be 'Dog' } } const myDog = new Dog(); console.log(myDog.species); // Output is expected to be 'Dog' ``` I also tried explicitly checking if `species` is defined in the console log, and it seems to be initialized correctly, but if I add more properties or methods in the `Dog` class, they don't seem to behave as expected. For instance, when I add a method to fetch the name of the dog, it throws an behavior because I mistakenly referred to a property that hasn't been initialized properly: ```typescript class Dog extends Animal { name: string; constructor(name: string) { super('Dog'); this.name = name; } getDogInfo() { return `${this.species} named ${this.name}`; } } const myDog = new Dog('Fido'); console.log(myDog.getDogInfo()); // This works fine ``` However, if I forget to pass a name when creating the `Dog` object, I get `TypeError: want to read properties of undefined (reading 'species')`. I thought that since I'm calling the constructor of the base class correctly, the `species` should always be initialized. Could anyone help clarify the intricacies of constructor overriding in TypeScript? Is there something I'm missing that leads to these unexpected behaviors? Thanks! This is part of a larger service I'm building. Thanks in advance! My development environment is Windows 10. Any suggestions would be helpful. Any suggestions would be helpful.