CodexBloom - Programming Q&A Platform

TypeScript: Class Inheritance Issues When Overriding Method with Different Parameter Types

πŸ‘€ Views: 66 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-17
typescript class inheritance TypeScript

I'm stuck on something that should probably be simple. I'm working with an scenario with TypeScript class inheritance where I'm trying to override a method in a subclass, but I'm getting a type behavior related to parameter types. The base class `Animal` has a method `speak` that accepts a string, but when I try to override it in the `Dog` subclass to accept an object instead, TypeScript throws an behavior. Here’s what I have so far: ```typescript class Animal { speak(sound: string): void { console.log(`The animal makes a sound: ${sound}`); } } class Dog extends Animal { speak(sound: { bark: string }): void { console.log(`The dog barks: ${sound.bark}`); } } ``` When I attempt to create an instance of `Dog` and call `speak`, like this: ```typescript const myDog = new Dog(); myDog.speak({ bark: 'Woof!' }); ``` I get the following behavior: ``` Argument of type '{ bark: string; }' is not assignable to parameter of type 'string'. ``` I've tried changing the method in the subclass to match the parameter type of the base class, but this defeats the purpose of overriding. I thought TypeScript allowed method overriding with different parameter types as long as they are compatible. Am I missing something in terms of TypeScript's rules around method overriding, or is there a different pattern I should be using here? Any suggestions on how to resolve this while maintaining clear object-oriented principles would be greatly appreciated! For context: I'm using Typescript on Windows 11. Thanks, I really appreciate it! Am I approaching this the right way? My development environment is CentOS. Cheers for any assistance! I'd really appreciate any guidance on this.