Mapped Types
Building new object types by transforming every key of an existing type.
Mapped types iterate over the keys of an existing type and produce a new type. They are how Partial, Readonly, and Required are built.
keyof T produces the key union. [K in keyof T] loops over those keys.
type User = {
id: string;
name: string;
email: string;
};
type Listify<T> = {
[K in keyof T]: T[K][];
};
type UserLists = Listify<User>;
// { id: string[]; name: string[]; email: string[] }Modifier prefixes add or remove readonly and optional markers.
type Config = {
readonly host: string;
debug?: boolean;
};
type Mutable<T> = {
-readonly [K in keyof T]: T[K];
};
type Complete<T> = {
[K in keyof T]-?: T[K];
};In production
Write a mapped type when the same optional, required, readonly, or value transformation appears more than once. The type disappears at runtime, but the consistency remains at every callsite.
Enjoyed this? Get more software craft delivered to your inbox.