CodexBloom - Programming Q&A Platform

Inheritance implementing TypeScript classes and method overriding in a complex hierarchy

πŸ‘€ Views: 94 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-16
typescript class inheritance TypeScript

I'm sure I'm missing something obvious here, but I've been struggling with this for a few days now and could really use some help... I've encountered a strange issue with I'm running into a question with method overriding in TypeScript when dealing with a complex class hierarchy. I have a base class `Animal`, and two derived classes `Dog` and `Cat`. Each derived class has a method `speak()` that overrides the base class method. However, when I try to call `speak()` on a `Dog` instance, it sometimes throws an behavior related to type incompatibility, specifically 'Property 'speak' does not exist on type 'Animal'.' Here's the code I have: ```typescript class Animal { speak(): string { return "Generic animal sound"; } } class Dog extends Animal { speak(): string { return "Woof"; } } class Cat extends Animal { speak(): string { return "Meow"; } } function makeAnimalSpeak(animal: Animal) { console.log(animal.speak()); } const dog = new Dog(); makeAnimalSpeak(dog); const cat: Animal = new Cat(); makeAnimalSpeak(cat); ``` This code works fine, but when I try to add a method `describe()` in the `Animal` class that calls `speak()`, I get the type behavior. Here’s the modification: ```typescript class Animal { speak(): string { return "Generic animal sound"; } describe(): string { return this.speak(); } } ``` After adding `describe()`, when I call `describe()` on a `Dog` instance `(dog.describe())`, it works as expected. However, when I try to pass `Dog` as a parameter where `Animal` is expected, it throws an behavior saying `Dog` might not have `describe()`β€”even though it does inherit from `Animal`. Is this a TypeScript scenario with method resolution in inheritance? I've tried ensuring that my `Animal` type is always being used, but I'm not sure if there's something wrong with how TypeScript resolves the types at runtime. Any insights into how I might solve this scenario or improve my design to avoid this confusion would be greatly appreciated. Any pointers in the right direction? The project is a application built with Typescript. What are your experiences with this?