Mapped types | Typescript

A common task is to take an existing type and make each of its properties optional:

type Readonly<T> = {
readonly [P in keyof T]: T[P];
}
type Partial<T> = {
[P in keyof T]?: T[P];
}

And to use it:

type PersonPartial = Partial<Person>;
type ReadonlyPerson = Readonly<Person>;

Note that this syntax describes a type rather than a member. If you want to add members, you can use an intersection type:

// Use this:
type PartialWithNewMember<T> = {
[P in keyof T]?: T[P];
} & { newMember: boolean }
// **Do not** use the following!
// This is an error!
type PartialWithNewMember<T> = {
[P in keyof T]?: T[P];
newMember: boolean;
}

This is a good template for any general use of mapped types. That's because this kind of transformation is homomorphic, which means that the mapping applies only to properties of T and no others. The compiler knows that it can copy all the existing property modifiers before adding any new ones. For example, if Person.name was readonly, Partial<Person>.name would be readonly and optional.

Note that Readonly<T> and Partial<T> are so useful, they are included in TypeScript's standard library along with Pick and Record:

type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}
type Record<K extends keyof any, T> = {
[P in K]: T;
}

Readonly, Partial and Pick are homomorphic whereas Record is not. One clue that Record is not homomorphic is that it doesn't take an input type to copy properties from:

type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>

Non-homomorphic types are essentially creating new properties, so they can't copy property modifiers from anywhere.