CodexBloom - Programming Q&A Platform

TypeScript: How to properly implement a generic class with constraints on type parameters?

👀 Views: 219 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-25
typescript generics class type-inference TypeScript

I've spent hours debugging this and I'm working through a tutorial and I need help solving After trying multiple solutions online, I still can't figure this out. I'm trying to create a generic class in TypeScript that accepts a type parameter constrained to a specific interface, but I'm running into issues with method implementation and type inference. Here's a simplified version of what I have: ```typescript interface Entity { id: number; name: string; } class Repository<T extends Entity> { private items: T[] = []; add(item: T): void { this.items.push(item); } getById(id: number): T | null { const item = this.items.find(item => item.id === id); return item || null; } } class User implements Entity { constructor(public id: number, public name: string) {} } const userRepo = new Repository<User>(); userRepo.add(new User(1, 'Alice')); const user = userRepo.getById(1); console.log(user); ``` While this implementation seems straightforward, I'm finding that when I try to add a method like `removeById`, TypeScript gives me an behavior regarding the type parameter: ```typescript removeById(id: number): void { this.items = this.items.filter(item => item.id !== id); } ``` When I attempt to call `removeById` or any similar methods, I receive an behavior `Argument of type 'number' is not assignable to parameter of type 'T'` which doesn't seem to make sense since `T` is constrained to `Entity`. I've tried modifying the method signature and ensuring that `id` is always a number, but I need to seem to resolve the type mismatch. Can anyone help clarify why this is happening and how I can properly implement the `removeById` method? I'm using TypeScript version 4.5 and I'm aware that generics can be tricky, but I feel like I'm missing something fundamental here. This is part of a larger microservice I'm building. What's the correct way to implement this? I'm working on a microservice that needs to handle this. Could this be a known issue? Thanks for your help in advance!