Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript Mapped Types: Syntax, Key Remapping with as, and Modifiers

How mapped types iterate over keys, add and remove readonly and optional modifiers, and use the as clause to rename keys or drop properties entirely with never.

~5 min readTypeScript
#TypeScript#Generics#Utility Types
3D illustration of a transformer pipeline converting object keys into prefixed getter methods with glowing neon gears

A mapped type is a type-level loop: it iterates over the keys of a source type, applies a rule to each property, and produces a new object type. Partial, Required, Readonly, Pick, Omit, and Record are all mapped types, and the as clause that arrived in TypeScript 4.1 turns the same construct into a key transformer — the mechanism behind string-prefixed accessors, event-name maps, and getter interfaces generated from data shapes.

Quick Summary

  • The basic form is { [K in keyof T]: F<T[K]> }; homomorphic mapped types (those written [K in keyof T]) preserve modifiers and modifiers can be added or removed with + and -.
  • readonly and ? modifiers are controlled per iteration: readonly [K in keyof T], -readonly [K in keyof T], [K in keyof T]-?.
  • Key remapping (as) rewrites the key; returning never from it drops the property entirely, which is how filtering mapped types are written.
  • The remapped key can be any type assignable to PropertyKey, including a template literal type built from the original key and a string.
  • Arrays and tuples are object types with numeric-like keys, so a mapped type maps their elements — and tuples need special care because a naive mapping turns them into arrays.
  • Homomorphic mapped types distribute over unions and preserve property modifiers; a non-homomorphic mapped type ([K in SomeUnion]) creates a fresh object type and drops modifiers.
  • Filtering with as combined with keyof is the documented way to emulate Omit while keeping the exact key set.

Basic syntax and type signatures

typescript
type Mutable<T> = { -readonly [K in keyof T]: T[K] }; type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] }; // Key remapping with as. type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]; }; interface State { count: number; label: string } type StateGetters = Getters<State>; // { getCount: () => number; getLabel: () => string } // Filtering: return never to drop a key. type OnlyStrings<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K]; }; type S = OnlyStrings<{ a: string; b: number; c: "x" }>; // { a: string; c: "x" } // Modifier removal. type RequiredAndMutable<T> = { -readonly [K in keyof T]-?: T[K] };

string & K in the template literal is required because keyof T may include symbol or number keys, and only string keys can be interpolated into a template literal type. Without the intersection, Capitalize<K> rejects the whole mapping.

Comparison of mapped type forms

FormHomomorphicPreserves optional/readonlyDistributes over unionsTypical use
{ [K in keyof T]: T[K] }yesyesyesidentity, modifier edits
{ [K in keyof T]?: T[K] }yesadds optionalyespartial updates
{ -readonly [K in keyof T]: T[K] }yesremoves readonlyyesmutable copies
{ [K in Union]: V }nononodictionaries from a union
{ [K in keyof T as X]: T[K] }yesyesyesrenamed keys
{ [K in keyof T as never]: T[K] }yesyesyesempty object type
Record<K, V> (built-in)nononoexplicit key sets

The homomorphic row is the one that matters for surprises: { [K in keyof T]: ... } keeps ? and readonly unless the mapping writes them differently, while Record<keyof T, T[K]> drops both because it is not keyed by keyof T in the homomorphic position.

Practical edge cases and deep dives

1. Turning a config shape into a typed accessor interface

typescript
type Accessors<T> = { [K in keyof T & string as `get${Capitalize<K>}`]: () => T[K]; } & { [K in keyof T & string as `set${Capitalize<K>}`]: (value: T[K]) => void; }; interface Settings { theme: "light" | "dark"; fontSize: number; } const settings: Accessors<Settings> = { getTheme: () => "dark", setTheme: (v) => { /* ... */ }, getFontSize: () => 14, setFontSize: (v) => { /* ... */ }, }; settings.setTheme("light"); // ok // settings.setTheme("blue"); // error: not assignable to "light" | "dark" // settings.setFontSize("14"); // error: string is not a number

The intersection of two mapped types is what makes this scale: getters and setters stay independent, each keeps the exact value type of the source property, and the implementation object is checked against the combined shape. Because the template literal is built from the key type, adding a property to Settings immediately requires two new methods on every implementation.

2. Filtering with as never and why Omit is not the same

typescript
type OmitByValue<T, V> = { [K in keyof T as T[K] extends V ? never : K]: T[K]; }; interface Form { id: number; name: string; createdAt: Date; updatedAt: Date; onSubmit: () => void; } type Serialized = OmitByValue<Form, Date | Function>; // { id: number; name: string } — but the key type is what matters: type Keys = keyof Serialized; // "id" | "name"

Omit<T, K> renames around a key union, so it cannot express "drop the properties whose value is a Date". The as clause evaluates a type per key and uses never as the drop signal, which the compiler removes from the resulting key union. This is also the reason keyof after such a mapping is exact: Exclude-based Omit keeps the removed keys out of the type only through a second pass, while the as form never adds them.

3. Mapped types over tuples and arrays

typescript
type ArrayToTuple<T extends readonly unknown[]> = { [K in keyof T]: T[K]; }; // Homomorphic over a tuple keeps the tuple shape. type A = ArrayToTuple<[string, number]>; // [string, number] // Mapping to a fixed value type turns a tuple into an array-like object. type Flags<T extends readonly unknown[]> = { [K in keyof T]: boolean }; type B = Flags<["a", "b"]>; // [boolean, boolean] // Indexing a mapped tuple with `number` gives the element union. type Elem = Flags<["a", "b"]>[number]; // boolean // Array types: `keyof string[]` includes length, methods, and number. type Bare<T extends readonly unknown[]> = { [K in keyof T]: T[K] };

A homomorphic mapped type over readonly [A, B] stays a readonly tuple, which is why Promise.all returns a tuple of results rather than an array. Mapping over T[] yields another T[], and the method keys (push, map, length) map along with the elements but keep their original types because the mapping rule only changes the value type, not the key. Replacing the value type unconditionally on an array type breaks the methods, which is why library code constrains to readonly unknown[] and maps homomorphically.

4. Modifier surgery for update payloads

typescript
type Update<T, K extends keyof T> = Omit<T, K> & { [P in K]-?: T[P]; }; interface User { id: string; name: string; email?: string } type CreatePayload = Update<User, "name" | "email">; // { id: string; name: string; email: string } // note: `email` is now required; `id` is still required from Omit // The safer form for updates: make everything optional except the key. type Patch<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>> & { [P in K]-?: T[P] }; type UserPatch = Patch<User, "id">; // { id: string; name?: string; email?: string }

-? on a mapped type forces the property to be present, which is exactly what a "name may not be omitted but its value may be updated" rule needs. The union with Omit<T, K> is what carries the untouched properties through: a mapped type alone can only rewrite the keys in the source list.

5. Recursive mapped types for deep transforms

typescript
type DeepReadonly<T> = T extends (infer U)[] ? readonly DeepReadonly<U>[] : T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]> } : T; type DeepMutable<T> = T extends readonly (infer U)[] ? DeepMutable<U>[] : T extends object ? { -readonly [K in keyof T]: DeepMutable<T[K]> } : T; interface Tree { readonly name: string; readonly children: readonly Tree[]; } type Frozen = DeepReadonly<Tree>; // no assignment anywhere in the tree type Thawed = DeepMutable<Tree>; // every level assignable

The array branch must come first: object matches arrays too, and mapping their keys would rewrite length and the methods. readonly (infer U)[] handles both mutable and readonly input arrays, so one definition covers both. Deep recursive mapped types are the place where the compiler's instantiation depth limit matters most; constraining the input to concrete interfaces rather than open generics keeps the cost bounded.

Common mistakes and compiler errors

Error or symptomCauseFix
Type 'K' cannot be used to index type 'T'K in keyof T used without the mapping being homomorphicwrite [K in keyof T]: ... on the source type itself
Remapped key is never for all propertiesthe filter condition is inverted or the value type test is wrongcheck T[K] extends V ? never : K and the literal types involved
Type 'symbol' is not assignable to type 'string' in a template literal keykeyof T includes symbol or numberconstrain with keyof T & string
Optional properties disappear after a mappingthe mapping was not homomorphiciterate keyof T directly instead of Record<keyof T, ...>
readonly lost on array elementsthe mapping replaced the element type on an arrayuse a homomorphic map with a conditional branch for arrays
Tuple maps to boolean[] instead of [boolean, boolean]the mapped type is constrained to unknown[] and mapped as an arraykeep the parameter as a tuple type and map homomorphically
Type instantiation is excessively deepunbounded recursion through a generic objectadd a depth limit or a base case for primitives
Object literal may only specify known properties on the mapped resultthe remapped keys differ from what the literal usedcheck Capitalize/Uppercase output, and that as was applied to the right key

Two habits prevent nearly all of these. First, always test the mapped type with a keyof assertion — type _ = Expect<Equal<keyof Result, "a" | "b">> — because a mapped type that produces the right properties with a wrong key union still compiles everywhere and fails only when used as a key. Second, when the mapping adds or removes modifiers, write the modifier explicitly (+readonly, -?) so the intent is visible in the type and not inferred from the source.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.