Table of contents
- 1. Mapped Types in Action
- 2. Using Utility Types
- 3. Mapped Type Modifiers
- 4. Advanced Mapping
- 5. Example
TypeScript 2.1 introduced mapped types which allow you to build new types based on the properties of an existing type.
Mapped Types in Action
For example, you can create a mapped type that is the same keys as an existing type, except that all values are optional:
1 |
|
The PartialUser
from the code listed above is called a mapped type because it defines a mapping of existing properties to optional properties.
Using Utility Types
TypeScript already provides so-called utility types such as Partial
or Required
to transform the modifiers of all properties of a given type. We can make use of this to minimize our code example:
1 |
|
Mapped Type Modifiers
In TypeScript 2.8 property modifiers have been added to extend the capabilities of mapped types. In addition to the optional modifier (?
), a removing (-
) and adding (+
) have been introduced. This makes it possible to remove or add a previously added modifier.
Example
1 |
|
Advanced Mapping
It is possible to use type assertions in order to change property names of types completely.
Example
The following code makes use of the built-in Template Literal Type Capitalize
to change the property names of UserValidation
:
1 |
|
The mapped UserValidation
type is equivalent to:
1 |
|