How to use mapped types in TypeScript

· Category: TypeScript

Short answer

Mapped types create new types by iterating over keys of an existing type and producing transformed properties using the syntax { [K in Keys]: Type }.

Steps

  1. Iterate over keys: type Flags<T> = { [K in keyof T]: boolean };
  2. Make properties readonly: { readonly [K in keyof T]: T[K] }
  3. Make properties optional: { [K in keyof T]?: T[K] }
  4. Remove modifiers with -readonly and -?
  5. Remap keys with as in TypeScript 4.1+: { [K in keyof T as NewKey]: T[K] }

Tips

  • Combine mapped types with conditional types for powerful property-level transformations.
  • Use key remapping to rename or filter properties based on patterns.

Common issues

  • Mapped types over unions distribute over each member, which may be surprising when working with union object types.
  • Recursive mapped types require careful type alias declarations to avoid circularity errors.