CodexBloom - Programming Q&A Platform

TypeScript: How to extend a class with a generic type while maintaining type safety?

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

I've looked through the documentation and I'm still confused about I'm testing a new approach and I'm trying to debug I'm having a hard time understanding Quick question that's been bugging me - I'm having trouble extending a class in TypeScript with a generic type while ensuring type safety across method parameters and properties... I have a base class `BaseService` that takes a generic type `T`. I want to create a derived class `UserService` that specifically works with a `User` type, but I'm running into issues with type inference. Here’s what I have so far: ```typescript interface User { id: number; name: string; } class BaseService<T> { private items: T[] = []; add(item: T): void { this.items.push(item); } getAll(): T[] { return this.items; } } class UserService extends BaseService<User> { findById(id: number): User | undefined { return this.getAll().find(user => user.id === id); } } ``` When I try to create an instance of `UserService` and add a user, I get the following behavior: ``` Argument of type 'string' is not assignable to parameter of type 'User'. ``` This behavior occurs when I'm calling `add` with a user object. I checked the structure of the object I’m passing, and it matches the `User` interface. Here's how I’m using the `UserService`: ```typescript const userService = new UserService(); userService.add({ id: 1, name: 'John Doe' }); // this works userService.add({ id: 2, name: 'Jane Doe', age: 30 }); // this causes the behavior ``` The scenario arises because I'm trying to add an object with an extra property `age` that is not defined in the `User` interface. I want to know if there's a way to ensure that only valid `User` objects can be added to the `UserService` without running into errors like this. I've tried modifying the `add` method in `BaseService` to use a more permissive type, but that leads to loss of type safety. Any advice on the best way to handle this while keeping the generic nature of the base class? This is for a REST API running on CentOS. For reference, this is a production application. Is this even possible?