Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Type Operators

TypeScript mapped types

Reference for mapped types in TypeScript: the [K in keyof T] syntax, homomorphic mapping, mapping unions, arrays and tuples, and how built-in utility types use them.

A mapped type builds a new object type by looping over a union of keys and computing a type for each one. The loop is written [K in Keys]: ValueType. Most of the built-in utilities (Partial, Readonly, Pick, Record) are one-line mapped types.

When the keys come from keyof T the mapping is homomorphic: it preserves the readonly and optional modifiers of the original properties and works on arrays and tuples element by element. Any other key union produces a fresh object type.

TypeScript
type Flags<T> = { [K in keyof T]: boolean };
type F = Flags<{ a: string; b: number }>; // { a: boolean; b: boolean }

Try it

TypeScript Writing your own utilities

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Mapping unions, arrays and tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
type Mapped<T> = {
  [K in KeyUnion]: ValueType;
};
type Mapped2<T> = {
  readonly [K in keyof T]?: T[K];
};
Part Description
K A type parameter that takes each member of the key union in turn.
KeyUnion string, number or symbol literals, or keyof T.
ValueType Any type; it may use K and, for homomorphic maps, T[K].
readonly / ? Optional modifiers, see mapping modifiers.

Edge cases: a key union that includes string produces an index signature. as clauses can rename or drop keys; see key remapping.

Usage notes

  • Homomorphic maps keep modifiers. { [K in keyof T]: T[K] } is a copy of T with the same readonly and ? flags.
  • Pick-style maps are not homomorphic in the same way for a free K extends keyof T, but TypeScript still preserves modifiers when K is constrained to keyof T.
  • Arrays and tuples are mapped element-wise only when the map is homomorphic over a generic T.
  • Primitives pass through: Partial<string> is string.
  • Recursion is allowed for deep versions, but be careful with functions and class instances, which become object types of their own properties.
  • Cannot add extra properties in the same mapped type; intersect with another object type instead.
  • Distribution: homomorphic mapped types distribute over a union T.
  • Compile-time only.