Conditional and mapped

Contents

Conditional and mapped#

Conditional types branch on type relationships; mapped types walk over keys.

Conditional type with extends.

type IsArray<T> = T extends unknown[] ? true : false;
type A = IsArray<number[]>;          // true
type B = IsArray<string>;            // false

Mapped type that strips readonly.

type Mutable<T> = {
  -readonly [K in keyof T]: T[K];
};

Mapped type that adds | null to every property.

type Nullable<T> = {
  [K in keyof T]: T[K] | null;
};

infer binds a sub-type inside a conditional.

type ElementOf<T> = T extends (infer U)[] ? U : never;
type N = ElementOf<number[]>;        // number

References#

  • Type operators for the related built-in helpers (Partial, Pick, Awaited, ReturnType).

  • Generics for parameterising over T.