Skip to the content.

Chapter 6: keyof, Indexed Access and Mapped Types

Runnable examples: examples/ch06-mapped-types.ts

Mapped types are loops over keys. Most of TypeScript’s utility types (Partial, Readonly, Pick, Record) are a single mapped type.

The building blocks

interface User { id: number; name: string; email?: string; readonly createdAt: Date }

type K = keyof User;              // "id" | "name" | "email" | "createdAt"
type V = User["id" | "name"];     // number | string  (indexed access with a union)
type All = User[keyof User];      // every property type

A mapped type

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

Read it as: for each key K in keyof T, produce a property named K, optional, with the type T[K].

Re-implementing the built-ins is the best exercise to understand them:

type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyRecord<K extends PropertyKey, V> = { [P in K]: V };

The examples verify with Expect<Equal<...>> that each one matches the built-in exactly.

Adding and removing modifiers

Prefix readonly or ? with - to remove them, + (the default) to add them:

type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Complete<T> = { [K in keyof T]-?: T[K] };  // like the built-in Required

Key remapping with as

Since TypeScript 4.1, you can rename keys while mapping:

type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
// Getters<{ id: number; name: string }> = { getId: () => number; getName: () => string }

string & K is needed because keyof T can include number and symbol keys, and template literal types need strings.

Mapping a key to never removes it, which gives you filtering:

type PickByValue<T, V> = { [K in keyof T as T[K] extends V ? K : never]: T[K] };

Homomorphic mapped types preserve modifiers

A mapped type over keyof T (directly) is called homomorphic. It keeps each property’s ? and readonly from T:

type Copy<T> = { [K in keyof T]: T[K] };
type Same = Copy<User>; // email is still optional, createdAt still readonly

Mapping over a plain union of keys that is not tied to T loses them:

type NonHomomorphic = { [K in "id" | "email"]: User[K] };
// email is now REQUIRED (with type string | undefined)

type Picked = Pick<User, "id" | "email">;
// email stays optional: Pick maps over K extends keyof T, which keeps the link to T

When a utility unexpectedly makes everything required, this is usually why.

Homomorphic mapped types also map over arrays and tuples element-wise instead of over their methods, which is why Readonly<[number, string]> gives readonly [number, string].

Pairing types with runtime code

A mapped type often describes what a runtime function produces:

function makeGetters<T extends Record<string, unknown>>(obj: T): Getters<T> {
  const result: Record<string, () => unknown> = {};
  for (const key of Object.keys(obj)) {
    result[`get${key.charAt(0).toUpperCase()}${key.slice(1)}`] = () => obj[key];
  }
  return result as Getters<T>;
}

The body needs a cast, because TypeScript cannot verify that string manipulation at runtime matches Capitalize at the type level. Keep such casts small and cover them with tests, as this repository does in test/runtime.test.ts.

Recursive mapped types

type DeepReadonly<T> = T extends (...args: any[]) => any
  ? T
  : T extends object
    ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
    : T;

The function check comes first so methods are left alone. Note that readonly is a compile-time promise only; to freeze at runtime, use Object.freeze (which is shallow).

Check yourself

  1. Why is string & K needed in the Getters key remapping?
  2. How do you remove a key in a mapped type?
  3. What does “homomorphic” preserve?
Answers 1. `keyof T` may include number and symbol keys; `Capitalize` and template literals need strings. 2. Remap it to `never` with `as`. 3. Optional and readonly modifiers of the original properties (and array or tuple shape).

Next: Chapter 7, Template Literal Types