TypeScript: Mapped types reference
2 December 2022 (Updated 13 August 2023)
On this page
In a nutshell
A mapped type is a generic type that uses a union of property keys (usually created via the keyof
operator) to iterate through keys to create a new type.
Mapped types are useful for creating a new type that uses the properties of another type. As an example, suppose you had the following FeatureConfig
type where each property is a function:
type FeatureConfig = {
darkMode: () => void;
betaDashboard: () => void;
}
// Maybe you use the FeatureConfig type as an argument:
// function configure(config: FeatureConfig) {}
You can use mapped types to create a new type that uses the same properties but where the types of the properties are booleans instead:
type FeatureConfig = {
darkMode: () => void;
betaDashboard: () => void;
}
type ConfigFlags<Type> = {
[Property in keyof Type]: boolean
}
type FeatureFlags = ConfigFlags<FeatureConfig>
// FeatureFlags is now equal to { darkMode: number; betaDashboard: number }
To create a mapped type then, you typically:
- Accept a generic type (e.g.,
MyNewType<Type> = {...}
- Use something like
[Property in keyof Type]: <new-type>
to create new types based on the keys of the generic type.
See an example of mapped types here.
Sources
Tagged:
TypeScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment