Mapped Types
One common task is to take an existing type and make each of its properties entirely optional.Let’s say we have a `Person:
interface Person {
name: string;
age: number;
location: string;
}
A partial version of it would be:
interface PartialPerson {
name?: string;
age?: number;
location?: string;
}
with Mapped types, PartialPerson
can be written as a generalized transformation on the type Person
as:
type Partial<T> = {
[P in keyof T]?: T[P];
};
type PartialPerson = Partial<Person>;
Mapped types are produced by taking a union of literal types, and computing a set of properties for a new object type.They’re like list comprehensions in Python, but instead of producing new elements in a list, they produce new properties in a type.
In addition to Partial
, Mapped Types can express many useful transformations on types:
// Keep types the same, but make each property to be read-only.
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
// Same property names, but make the value a promise instead of a concrete one
type Deferred<T> = {
[P in keyof T]: Promise<T[P]>;
};
// Wrap proxies around properties of T
type Proxify<T> = {
[P in keyof T]: { get(): T[P]; set(v: T[P]): void }
};