AI Hints
Home›TypeScript Tutorial›Generics Practice and keyof
TypeScript · Lesson 58 of 120

Practice: A Typed Store

Generics together.

⏱ 2 min read▶ Video at 45:01🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

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.

Practice: A Typed Store
From the video: Practice: A Typed Store
  • 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