Sub topic 11
How TypeScript Utility Types Are Built: Mapped Types
This chapter assumes you know interfaces, type aliases, unions, literal types, generics, and basic keyof syntax. You will learn the working model behind object utility types such as Partial, Required, Readonly, Pick, and Record.
The basic idea
A mapped type creates a new object type by visiting each property in another type. It uses three parts:
keyof Tproduces a union of the property names inT.K in keyof Tloops over those property names.T[K]looks up the type of the current property.
For example:
interface User {
id: number;
name: string;
email?: string;
}
type PropertyTypes = {
[K in keyof User]: User[K];
};
// {
// id: number;
// name: string;
// email?: string | undefined;
// }PropertyTypes has the same shape as User. The mapped type copied every key and its corresponding value type.
Mapped type modifiers
Mapped types can add or remove property modifiers. A modifier changes whether a property is optional or readonly.
| Syntax | Effect |
|---|---|
| `?` | Add optionality |
| `-?` | Remove optionality |
| `readonly` | Prevent reassignment |
| `-readonly` | Remove readonly |
The built-in utility types are short mapped types:
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];
};
interface User {
id: number;
name: string;
email?: string;
}
const draft: MyPartial<User> = { name: "Ada" };
const complete: MyRequired<User> = {
id: 1,
name: "Ada",
email: "[email protected]",
};
const locked: MyReadonly<User> = {
id: 1,
name: "Ada",
};
// locked.name = "Grace"; // ErrorThe -? modifier matters because Required must remove optionality from every property. Without it, optional properties would remain optional.
Restricting the keys
A mapped type does not have to use every key. Pick maps over a selected key union:
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};
type UserPreview = MyPick<User, "id" | "name">;
// { id: number; name: string }The constraint K extends keyof T prevents callers from selecting a property that does not exist.
Record uses a key union and gives every key the same value type:
type MyRecord<K extends PropertyKey, V> = {
[P in K]: V;
};
type Role = "admin" | "editor" | "viewer";
const permissions: MyRecord<Role, string[]> = {
admin: ["read", "write"],
editor: ["read"],
viewer: ["read"],
};Because Role contains three literal keys, omitting one creates a type error.
Conditional logic in custom utilities
Mapped types can combine with conditional types to transform each property differently. This example makes every property nullable:
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
interface Settings {
theme: string;
fontSize: number;
}
const settings: Nullable<Settings> = {
theme: null,
fontSize: 16,
};The expression T[K] | null is evaluated separately for each key. Thus theme becomes string | null, while fontSize becomes number | null.
Key remapping
The as clause can rename or filter keys while mapping:
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;
// }string & K narrows the key to a string so that Capitalize can use it.
Exercise
Write a mapped type named Mutable<T> that removes readonly from every property.
Show answer
type Mutable<T> = { -readonly [K in keyof T]: T[K]; };