← Learning Hub
Intermediate

Generics

Generics let you write one function or type that works with many types while keeping them checked. The type is a parameter, written in angle brackets: <T>.

Generics let you write code once that works for many types without losing type safety - like a box that can hold any item but remembers what kind of item it is. Arrays (Array<T>), promises (Promise<T>) and most libraries use them.

Example
You can edit this code.

Generic interfaces

Example
You can edit this code.

Constraints with extends

Sometimes T must have certain properties. T extends ... sets the minimum:

Example
You can edit this code.

A generic class

Example
You can edit this code.
Key points
  • <T> is a type parameter.
  • Generic functions, interfaces and classes keep types precise.
  • extends adds constraints to T.

📝 Test yourself

1. Why use generics?
2. What does T extends { price: number } mean?
3. Fill in the generic type for a list of strings:
const res: ApiResponse<> = { ok: true, data: ["a"] };