Reputation: 36600
How does it work? When should I use it?
Upvotes: 2
Views: 3769
Reputation: 36600
In Typescript we sometimes want to build types based on other types. Mapped types allow us to generate new types based on existing types in a very concise manner which makes us adhere to the don't repeat yourself principle
Custom properties:
type customProperties = {
[key: string]: string | boolean;
};
const conforms: customProperties = {
str: 'foo',
bool: true,
// int: 123 > Error Type 'number' is not assignable to type 'string | boolean'.
};
Mapped types:
type Person = {
name: string;
age: string;
};
// Demo only >> TS has a builtin Readonly, use that
type myReadonly<Type> = {
readonly [Property in keyof Type]: Type[Property];
};
// Demo only >> TS has a builtin Partial, use that
type myPartial<Type> = {
[Property in keyof Type]?: Type[Property];
};
type ReadonlyPerson = myReadonly<Person>
type PartialPerson = myPartial<Person>
Note that mapped types is using the syntax []: type
of custom properties. the difference between the custom properties and the mapped type is the following:
[Property in keyof Type]
syntax. It maps all the properties of the existing type to the new type which you can customize according to your needs.Upvotes: 5