TypeScript · Lesson 58 of 120
Practice: A Typed Store
Generics together.
Let's practise generics with a small in memory store. It can hold bikes, customers, or anything with an ID, and every method stays fully typed.

- In-memory store
- Anything with an id
- Fully typed
A generic store
Store of T requires T to have a numeric ID. It keeps items in a map. Save and find are typed with T. A bike store returns bikes, so the model is available. Run it.
app.tstypescript
class Store<T extends { id: number }> {
private items = new Map<number, T>();
save(item: T): void {
this.items.set(item.id, item);
}
find(id: number): T | undefined {
return this.items.get(id);
}
}
type Bike = { id: number; model: string };
const bikes = new Store<Bike>();
bikes.save({ id: 1, model: "Trail 500" });
bikes.save({ id: 2, model: "Volt 7" });
console.log(bikes.find(2)?.model, bikes.find(9));Output
Volt 7 undefined
Summary
A constrained generic class gives a reusable, fully typed store. Next, the generics quiz.
Key takeaways- Store<T extends {id}>
- Map<number, T>
- Typed results
Next up: Generics Quiz — test yourself