Mapped types | Typescript
A common task is to take an existing type and make each of its properties optional:
And to use it:
Note that this syntax describes a type rather than a member. If you want to add members, you can use an intersection type:
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:
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:
Non-homomorphic types are essentially creating new properties, so they can't copy property modifiers from anywhere.