TypeScript theorytheory 0/50 · 0%
Types · medium

24. Generic constraints (extends)

Restricting what a generic type parameter can be.

A generic type parameter can be constrained with `extends`, limiting which types are allowed and unlocking property access that would otherwise be unsafe.

ts
interface HasId { id: string; }

function findById<T extends HasId>(items: T[], id: string): T | undefined {
  return items.find(item => item.id === id);
}

interface Token extends HasId { symbol: string; }
const tokens: Token[] = [{ id: "1", symbol: "ETH" }];
findById(tokens, "1"); // T inferred as Token

Because `T extends HasId`, the compiler allows `item.id` inside the function body. Without the constraint, `T` could be anything, and `.id` wouldn't be guaranteed to exist. `keyof` is often combined with constraints, e.g. `function pick<T, K extends keyof T>(obj: T, key: K): T[K]`.

Check your understanding

  1. 1. What does `<T extends HasId>` mean?

  2. 2. Why is the constraint needed to access `item.id` inside the function?

  3. 3. What does `K extends keyof T` typically constrain K to?