Dmytro Morar
TypeScript

Conditional types

Conditional types choose a result based on a type relationship, similar to A extends B ? X : Y.

Syntax

T extends U ? X : Y
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>; // "yes"
type B = IsString<number>; // "no"

Utility types

Many built-ins use this pattern.

type Exclude<T, U> = T extends U ? never : T;
type Result = Exclude<"a" | "b" | "c", "a" | "c">; // "b"

Nested checks

type Check<T> = T extends string
  ? "string"
  : T extends number
  ? "number"
  : "other";

On this page