CodexBloom - Programming Q&A Platform

TypeScript: How to Extend a Class with Abstract Properties and Maintain Type Safety?

πŸ‘€ Views: 385 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
typescript oop abstract-classes

I'm stuck on something that should probably be simple. I'm sure I'm missing something obvious here, but I'm working on a TypeScript application where I'm trying to create a base class with abstract properties... I want to create a derived class that extends this base class, but I'm running into issues with type safety. My base class, `Animal`, has an abstract property `sound`, and the derived class `Dog` needs to implement this property. However, when I try to instantiate `Dog`, TypeScript throws an behavior. Here's a simplified version of my code: ```typescript abstract class Animal { abstract sound: string; makeSound(): string { return this.sound; } } class Dog extends Animal { sound = "Woof"; } const myDog = new Dog(); console.log(myDog.makeSound()); // Should log "Woof" ``` This works fine, but when I try to create a second derived class, `Cat`, and implement it like this: ```typescript class Cat extends Animal { sound = 123; // This should be a string } ``` TypeScript correctly flags this with an behavior: `Type 'number' is not assignable to type 'string'`. However, I'm confused because I thought TypeScript would allow any property to be defined as long as it aligns with the base class signature. When I try to make the property a `string | number`, I face issues with the method `makeSound` that operates on `string` only. What’s the best way to enforce type safety while allowing flexibility in derived classes? Is there a design pattern that can guide to avoid these conflicts? I'm using TypeScript 4.5.2, and I’m open to suggestions about refactoring my approach to this question. I'm working on a API that needs to handle this. For context: I'm using Typescript on macOS. Any help would be greatly appreciated! I'd really appreciate any guidance on this.