Advanced TypeScript

Mapped Types

Mapped types transform object types by iterating over keys. They are how TypeScript expresses mechanical object-shape changes such as readonly, optional, required, picked, omitted, and remapped properties.
  • Mapped types iterate over keys
  • Indexed access gets property value types
  • Modifiers can be added or removed
  • Keys can be remapped
  • Mechanical transformation is not semantic design
Basic mapped types
type Mutable<T> = {
  -readonly [K in keyof T]: T[K]
}

type Nullable<T> = {
  [K in keyof T]: T[K] | null
}
The new type follows the keys of the original type.
Key remapping
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
}

type UserGetters = Getters<{ id: string; name: string }>
// { getId: () => string; getName: () => string }
Mapped types can generate new property names from old ones.
Mapped type tools
ToolUse
keyof TGet key union
K in keyof TIterate keys
T[K]Read property value type
readonly / -readonlyAdd/remove readonly
? / -?Add/remove optional
asRemap/filter keys
Sources
  • The TypeScript HandbookMapped Types
  • Effective TypeScript, 2nd EditionType-level programming
  • TypeScript ReferenceKeyof and indexed access