Skip to content

Lesson 5 of 9 · 23m

Mapped Types: Transforming Shapes Without Copy-Paste

Key remapping, modifiers, and selective transformation — the machinery behind Pick, Omit, Partial, and precise domain-specific object types.

Mapped types are TypeScript's answer to a familiar maintenance problem: you have one authoritative object shape, and five derived shapes that must stay synchronized with it. Writing those derived interfaces by hand works until a refactor misses one. Then the compiler stays quiet while production pays the bill.

A mapped type iterates over keys

type ReadonlyUser = { readonly [K in keyof User]: User[K] };

For each key K in keyof User, the resulting object has the same key and value type. TypeScript's built-ins are exactly this idea:

type PartialUser = Partial<User>;      // every field optional
type UserPreview = Pick<User, "id" | "displayName">;
type UserSecrets = Omit<User, "id" | "displayName">;

The important lesson is not memorizing utility types. It is recognizing when a shape is derived and making the derivation explicit.

Add and remove modifiers deliberately

type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type RequiredFields<T> = { [K in keyof T]-?: T[K] };

The - removes readonly or optionality. This matters in integration boundaries where frameworks produce readonly route state but your mutation helpers need a draft copy.

Key remapping turns objects into vocabularies

as inside a mapped type renames or filters keys:

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

type UserGetters = Getters<{ id: string; displayName: string }>;
// { getId: () => string; getDisplayName: () => string }

Filtering keys is just remapping to never:

type OnlyFunctions<T> = {
  [K in keyof T as T[K] extends (...args: never[]) => unknown ? K : never]: T[K];
};

This is how mature libraries build ergonomic APIs without duplicating interfaces.

Field notes

  • keyof on an intersection can produce surprising unions; test object transformations with realistic data shapes.
  • Homomorphic mapped types preserve modifiers automatically; once you remap keys, TypeScript may drop optional/readonly behavior unless you reapply it.
  • Keep transformed types close to the original model and derive exported API types from it.
  • If you need Omit on a discriminated union, distribute it yourself or the discriminator relationship can collapse.

Was this lesson helpful?

Sign in to rate