Build type-safe generic classes with constraints and inference
typescript
TypeScript - Generic Class with Constraints
interface Repository<T extends { id: string }> {
find(id: string): Promise<T | null>
findAll(): Promise<T[]>
create(data: Omit<T, 'id'>): Promise<T>
update(id: string, data: Partial<T>): Promise<T>
delete(id: string): Promise<void>
}
class InMemoryRepository<T extends { id: string }> implements Repository<T> {
private items = new Map<string, T>()
async find(id: string): Promise<T | null> {
return this.items.get(id) ?? null
}
async findAll(): Promise<T[]> {
return Array.from(this.items.values())
}
async create(data: Omit<T, 'id'>): Promise<T> {
const id = crypto.randomUUID()
const item = { ...data, id } as T
this.items.set(id, item)
return item
}
async update(id: string, data: Partial<T>): Promise<T> {
const existing = await this.find(id)
if (!existing) throw new Error('Not found')
const updated = { ...existing, ...data }
this.items.set(id, updated)
return updated
}
async delete(id: string): Promise<void> {
this.items.delete(id)
}
}