TypeScript theorytheory 0/50 · 0%
Types · medium

26. Mapped types

Generating new object types by transforming each property.

A mapped type iterates over a union of keys (often `keyof T`) and produces a new property for each, optionally changing its modifiers or type.

ts
type Flags<T> = {
  [K in keyof T]: boolean;
};

interface Token { symbol: string; decimals: number; }
type TokenFlags = Flags<Token>; // { symbol: boolean; decimals: boolean }

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

type OptionalVersion<T> = {
  [K in keyof T]?: T[K];
};

This is exactly how built-ins like `Partial<T>` and `Readonly<T>` are implemented internally. You can also add `as` clauses to rename keys (key remapping), e.g. `[K in keyof T as `get${string & K}`]: () => T[K]` to generate getter method names.

Check your understanding

  1. 1. What does `[K in keyof T]: boolean` do?

  2. 2. Which built-in utility types are implemented using mapped types?

  3. 3. What does an `as` clause in a mapped type enable?