TypeScript · Lesson 4
Mapped Types
Transform object types key by key - Partial, Pick, Record and friends, modifiers, key remapping with as, and getters-style transforms.
In short
- A mapped type loops over a key union to build an object type
- Mapping
keyof Tpreserves?andreadonly +and-add or remove modifiersasrenames keys; mapping toneverfilters them- Write the domain type once and derive the rest
A mapped type builds a new object type by iterating over a union of keys. It is TypeScript's Array.prototype.map for object types, and every utility type you use daily (Partial, Readonly, Pick, Record) is one.
The basic shape
type Flags<Keys extends string> = { [K in Keys]: boolean };
type Features = Flags<'darkMode' | 'beta'>; // { darkMode: boolean; beta: boolean }
K takes each member of the key union in turn, and the right-hand side may use it. Most of the time the keys come from another type:
type Nullable<T> = { [K in keyof T]: T[K] | null };
interface User { id: number; name: string; email?: string }
type NullableUser = Nullable<User>;
// { id: number | null; name: string | null; email?: string | null | undefined }
Homomorphic mapped types
A mapped type of the form { [K in keyof T]: ... } is called homomorphic: it maps an existing type's structure. Homomorphic mapped types have three special behaviours:
- They preserve modifiers:
?andreadonlyonT's properties carry over (noteemail?above). - They map arrays and tuples to arrays and tuples:
Nullable<[number, string]>is[number | null, string | null], not an object with"0","length"and"push"keys. - They distribute over unions when
Tis a type parameter:Partial<A | B>isPartial<A> | Partial<B>.
Modifiers: readonly and ?, with + and -
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] }; // remove optionality
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] }; // remove readonly
+ is the default and rarely written. -? also strips undefined from the property type (unless exactOptionalPropertyTypes is on), which is why Required<{ a?: number }> is { a: number }, not { a: number | undefined }.
The built-ins, implemented
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyRecord<K extends keyof any, V> = { [P in K]: V };
type MyOmit<T, K extends keyof any> = MyPick<T, Exclude<keyof T, K>>;
keyof any is string | number | symbol (also spelled PropertyKey). Note the asymmetry: Pick requires K extends keyof T, so typos are errors; Omit accepts any key, so Omit<User, 'emial'> silently does nothing. Many codebases define a StrictOmit<T, K extends keyof T>.
Is MyPick homomorphic? Yes, effectively: K extends keyof T lets TypeScript treat [P in K] as mapping T's properties, so Pick preserves ? and readonly too.
Key remapping with as
Since TS 4.1 a mapped type can compute a new key for each property:
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }
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] };
type StringFields = PickByValue<User, string>; // { name: string }
string & K is needed because keyof T may include number and symbol keys, and template literal types only accept string | number | bigint | boolean | null | undefined. Intersecting with string drops symbols.
You can also map over a union of objects and pick the key from each member:
type UiEvent = { type: 'click'; x: number } | { type: 'key'; code: string };
type ByType = { [E in UiEvent as E['type']]: E };
// { click: { type: 'click'; x: number }; key: { type: 'key'; code: string } }
Making results readable: Simplify
Utility compositions produce intersections like Pick<User, 'id'> & Partial<Omit<User, 'id'>>, which hover tooltips show verbatim. A tiny identity mapped type flattens them:
type Simplify<T> = { [K in keyof T]: T[K] } & {};
This matters beyond aesthetics: type-level tests using Equal treat A & B and the flattened object as different types even though they're mutually assignable.
Gotchas
Omitandkeyofon unions aren't distributive.keyof (A | B)is only the shared keys, soOmit<Shape, 'id'>on a discriminated union collapses it into one object with only common fields. Use a distributive version:type DistributiveOmit<T, K extends keyof any> = T extends unknown ? Omit<T, K> : never;(conditional types, next topic).- Index signatures:
keyof { [k: string]: number }isstring | number, and a homomorphic mapped type keeps the index signature. SoPartial<Record<string, X>>is still "any string key", andGetters<Record<string, X>>becomes a pattern index signature for`get${Capitalize<string>}`keys (getFoois allowed,getfooisn't). - Mapped types are shallow.
Readonly<Config>doesn't makeconfig.db.hostreadonly. Deep variants need recursion (next topic). - Methods vs properties: method parameters are checked bivariantly, while a property written as a function type (
save: (a: Animal) => void) gets the strict check understrictFunctionTypes. A mapped type keeps a method's bivariance (Partial<Saver>still accepts a(d: Dog) => voidforsave), so if you want the strict check, declare the member as a function-typed property.
In real codebases
Side note
Mapped types shine wherever one source type should drive several others: DTOs derived from entities (CreateUserDto = Omit<User, 'id' | 'createdAt'>, UpdateUserDto = Partial<CreateUserDto>), form state (errors: { [K in keyof Values]?: string }), typed API clients and event maps (on${Capitalize<K>} handlers), feature-flag and config objects, and ORMs (Prisma's generated Select/Include types are mapped types). The rule of thumb: write the domain type once, derive the rest, so a new field flows through every layer automatically.
Practise this lesson
In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app