Skip to the page

Generics and type-level tools · core

Generics and constraints

A generic is a type parameter that keeps the relationship between inputs and outputs (e.g. first<T>(xs: T[]): T | undefined), and extends constrains what can be passed in.

The notes

What you must know

  • function identity<T>(x: T): T keeps the exact type; (x: any) => any loses it.
  • Constraints: <T extends { id: string }> lets you read .id and still return the full T.
  • <K extends keyof T> ties a key to an object: get<T, K extends keyof T>(obj: T, key: K): T[K].
  • Usually let TypeScript infer type arguments; pass them explicitly only when inference can't (e.g. useState<User | null>(null)).
  • Defaults: <T = unknown>. const type parameters (TS 5.0) infer literal types: <const T>.

The red pen

Common traps: mistake → fix

  • Mistake: "generics are only for collections"

    Fix: they are for any function or component whose output type depends on its input type.

  • Mistake: "T extends X means T is exactly X"

    Fix: it means T is assignable to X and may have more properties.

Easy to hard

Questions interviewers ask, easy to hard

  1. What problem do generics solve? Show one you wrote.
  2. How do constraints work, with keyof?
  3. When must you pass a type argument explicitly?
  4. Write a typed groupBy.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview