TypeScript theorytheory 0/50 · 0%
Types · hard

38. Conditional types

Types that branch based on a type-level condition.

A conditional type has the form `T extends U ? X : Y`, evaluated at the type level rather than at runtime.

ts
type IsString<T> = T extends string ? true : false;
type A = IsString<"hi">;  // true
type B = IsString<42>;    // false

type Flatten<T> = T extends (infer U)[] ? U : T;
type C = Flatten<number[]>; // number
type D = Flatten<string>;   // string

`infer` introduces a new type variable inside the `extends` clause, letting you extract a piece of a type — `Flatten` pulls the element type out of an array, otherwise returns the type unchanged. Conditional types combined with `infer` power many of the utility types you use daily, like `ReturnType<T>` and `Parameters<T>`.

Check your understanding

  1. 1. What does `T extends U ? X : Y` represent?

  2. 2. What does `infer U` do inside a conditional type?

  3. 3. What does `Flatten<string>` evaluate to given `type Flatten<T> = T extends (infer U)[] ? U : T`?