Skip to the page

Generics and type-level tools · senior

Conditional types and infer

A conditional type picks a type by a test (T extends U ? X : Y), distributes over unions when T is a naked type parameter, and infer pulls a type out of another type (like the return type of a function).

The notes

What you must know

  • type IsString<T> = T extends string ? true : false.
  • Distributive: T extends any ? T[] : never applied to string | number gives string[] | number[]. Wrap in a tuple ([T] extends [any]) to stop distribution.
  • infer: type Ret<T> = T extends (...a: any[]) => infer R ? R : never (this is ReturnType). Awaited<T> unwraps promises recursively.
  • Used for: NonNullable, Extract, Exclude, typing library APIs. Don't overuse in app code: readability first.

The red pen

Common traps: mistake → fix

  • Mistake: "conditional types run at runtime"

    Fix: they only exist in the compiler.

  • Mistake: "Exclude works on object keys"

    Fix: it filters members of a union; use Omit for object keys.

Easy to hard

Questions interviewers ask, easy to hard

  1. How does ReturnType work?
  2. What does distributive mean, and how do you turn it off?
  3. Implement Awaited for nested promises.

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