Advanced · 3 of 12 · 16 min read
Mapped types
A loop over the keys of a type — the four modifiers you can add or remove, how as renames a key, and the clause that filters keys out entirely.
- Mapped types
A mapped type is a for loop over a union of keys that produces an object type. Every object-shaped
utility type in the standard library is one, and once the syntax is familiar the missing one is a
two-line write.
The loop
interface User {
id: number;
name: string;
email: string;
}
type Stringify<T> = { [K in keyof T]: string };
type Nullable<T> = { [K in keyof T]: T[K] | null };
type A = Stringify<User>; // { id: string; name: string; email: string }
type B = Nullable<User>; // { id: number | null; ... }
const b: B = { id: null, name: "Ana", email: null };
console.log(b.id, b.name);
K in keyof T binds K to each key in turn; T[K] is the indexed access that gets that key’s
type. Those two pieces are the whole vocabulary.
The source does not have to be keyof anything — any union of keys works, which is what Record
is:
type Role = "admin" | "user" | "guest";
type MyRecord<K extends PropertyKey, V> = { [P in K]: V };
type Permissions = MyRecord<Role, string[]>;
const permissions: Permissions = {
admin: ["read", "write"],
user: ["read"],
guest: [],
};
console.log(permissions.admin);
The modifiers
interface User { id: number; email?: string }
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type A = MyRequired<User>; // email is now required
type B = Mutable<Readonly<User>>;
const a: A = { id: 1, email: "x" };
const b: B = { id: 1 };
b.id = 2; // allowed — the readonly was removed
console.log(a.email, b.id);
? and readonly are additive by default, and -? / -readonly subtract. The + form exists
(+?, +readonly) and is never written, because it is the default.
-? does one thing people miss: removing the optionality also removes undefined from the
property’s type.
interface Config { timeout?: number }
type A = Required<Config>; // { timeout: number } — not number | undefined
const a: A = { timeout: 1 };
console.log(a.timeout.toFixed(0)); // no check needed
| Written | Effect |
|---|---|
[K in keyof T] |
iterate every key |
[K in keyof T]? |
make every property optional |
[K in keyof T]-? |
make every property required, and drop undefined |
readonly [K in keyof T] |
make every property readonly |
-readonly [K in keyof T] |
strip readonly |
[K in keyof T as NewKey] |
rename the key |
[K in keyof T as never] |
remove the key |
[K in Union] |
iterate an arbitrary key union |
Key remapping with as
interface User { name: string; age: number }
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number }
const api: UserGetters = {
getName: () => "Ana",
getAge: () => 30,
};
console.log(api.getName(), api.getAge());
string & K is the idiom that makes Capitalize happy: keyof T is
string | number | symbol, and the string-literal utilities only accept strings. The
intersection keeps the literal and discards the rest.
Mapping a key to never deletes it, which is how a filtered object type is built:
interface Mixed {
id: number;
name: string;
save(): void;
load(): void;
}
type DataOnly<T> = {
[K in keyof T as T[K] extends Function ? never : K]: T[K];
};
type Data = DataOnly<Mixed>; // { id: number; name: string }
const data: Data = { id: 1, name: "Ana" };
console.log(data);
That is the whole trick behind OmitByType, PickByType, “only the writable keys” and every
other selective transformation. The conditional lives in the key position, so it decides whether
the key exists at all — not just what its type is.
Selecting keys by their type
The same mechanism, the other way round:
interface Form {
name: string;
age: number;
email: string;
}
type KeysOfType<T, V> = {
[K in keyof T]: T[K] extends V ? K : never;
}[keyof T];
type StringKeys = KeysOfType<Form, string>; // "name" | "email"
const key: StringKeys = "email";
console.log(key);
Read it inside out: the mapped type produces { name: "name"; age: never; email: "email" }, and
then [keyof T] takes the union of all its values — where the nevers disappear. That
“map-then-index” shape is the standard way to get a union out of an object type.
Homomorphic mapping
A mapped type written over keyof T is homomorphic, which has three consequences worth
knowing because they look like special-casing:
type Wrap<T> = { [K in keyof T]: T[K][] };
type A = Wrap<[string, number]>; // [string[], number[]] — still a tuple
type B = Wrap<string[]>; // string[][] — still an array
interface User { readonly id: number; name?: string }
type C = Wrap<User>; // readonly and ? are preserved
const a: A = [["x"], [1]];
console.log(a);
Arrays and tuples stay arrays and tuples rather than becoming objects with numeric keys, and the
existing modifiers are carried over instead of being reset. Write the source as a plain union of
keys instead of keyof T and all three go away:
interface User { readonly id: number }
type Homomorphic<T> = { [K in keyof T]: T[K] };
type NotHomomorphic<T> = { [K in keyof T as K]: T[K] };
type A = Homomorphic<User>; // { readonly id: number }
type B = NotHomomorphic<User>; // { id: number } — readonly lost
const b: B = { id: 1 };
b.id = 2;
console.log(b.id);
That is also the practical way to strip modifiers when you want them gone.
A worked example
Two mapped types that earn their keep in a real codebase:
type Events = {
click: { x: number; y: number };
keypress: { key: string };
};
type Handlers = {
[K in keyof Events as `on${Capitalize<K & string>}`]?: (event: Events[K]) => void;
};
type Emitter = {
[K in keyof Events as `emit${Capitalize<K & string>}`]: (event: Events[K]) => void;
};
const handlers: Handlers = {
onClick: (event) => console.log(event.x, event.y),
};
declare const emitter: Emitter;
handlers.onClick?.({ x: 1, y: 2 });
console.log(typeof emitter.emitKeypress);
One Events map, and both the handler shape and the emitter shape are derived from it. Add an
event and both grow; the alternative is three declarations that drift.
Common mistakes
Mapping over an array with a key union
Mistake. { [K in keyof T as K]: ... } applied to string[].
Why it fails. The as makes it non-homomorphic, so the array becomes an object with length,
push and every array method as properties.
What to do instead. Keep [K in keyof T] without as, or handle the array case in a
conditional before mapping.
Capitalize<K> directly
Mistake. Using K from keyof T inside a string-literal utility.
Why it fails. keyof T includes number and symbol, which Capitalize rejects.
What to do instead. Capitalize<string & K>, or constrain the source to
Extract<keyof T, string>.
Expecting the map to be deep
Mistake. Readonly<T> for a nested configuration object.
Why it fails. The loop runs once, over the top-level keys. Nested objects are untouched.
What to do instead. Recurse — a conditional type that maps and then calls itself, with an
explicit base case for arrays, Date and functions.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does { [K in keyof T]: T[K] } describe?
A mapped type can add or remove a modifier, and the minus sign is how you remove one.
What does { -readonly [K in keyof T]-?: T[K] } produce?
interface User {
readonly id: number;
name?: string;
}What does the as clause in { [K in keyof T as NewKey]: T[K] } allow?
Mapping over a type usually loses what made it special.
Why does mapping over an array type produce something unusable?
type Wrapped<T> = { [K in keyof T]: T[K] | null };
type A = Wrapped<string[]>;Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.