CodexBloom - Programming Q&A Platform

implementing TypeScript class generics and method overriding when using inheritance

πŸ‘€ Views: 97 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
typescript generics inheritance TypeScript

Can someone help me understand I'm working on a personal project and I tried several approaches but none seem to work. I'm working with an scenario with generics in TypeScript while trying to override a method in a subclass. I have a base class with a generic method that returns an array of items, and I want to override this method in a derived class to return a specific type of items. However, I am getting a type behavior related to the return type of the method. Here’s a simplified version of my code: ```typescript class Base<ItemType> { getItems(): ItemType[] { return []; } } class Derived extends Base<string> { getItems(): string[] { return ["item1", "item2"]; } } const instance = new Derived(); const items = instance.getItems(); // works fine ``` This works correctly, but when I try to add another layer of inheritance: ```typescript class FurtherDerived extends Derived { getItems(): number[] { return [1, 2, 3]; } } const furtherInstance = new FurtherDerived(); const furtherItems = furtherInstance.getItems(); // behavior here ``` I get the following behavior message: ``` Type 'number[]' is not assignable to type 'string[]'. ``` It seems TypeScript is retaining the return type from the `Derived` class instead of allowing me to specify a different type in `FurtherDerived`. I've tried using generics in `FurtherDerived` as well: ```typescript class FurtherDerived<ItemType> extends Derived { getItems(): ItemType[] { return [1, 2, 3] as unknown as ItemType[]; } } ``` This approach leads to other type-related issues. How can I correctly override the `getItems` method while ensuring the base class's generic nature is respected and doesn't restrict the derived class's functionality? I'm using TypeScript version 4.5.2. Is there a better approach? Any ideas what could be causing this? I'm working with Typescript in a Docker container on Linux.