How to use mapped types in TypeScript
· Category: TypeScript
Short answer
Mapped types create new types by iterating over keys of an existing type and producing transformed properties using the syntax { [K in Keys]: Type }.
Steps
- Iterate over keys:
type Flags<T> = { [K in keyof T]: boolean }; - Make properties readonly:
{ readonly [K in keyof T]: T[K] } - Make properties optional:
{ [K in keyof T]?: T[K] } - Remove modifiers with
-readonlyand-? - Remap keys with
asin TypeScript 4.1+:{ [K in keyof T as NewKey]: T[K] }
Tips
- Combine mapped types with conditional types for powerful property-level transformations.
- Use key remapping to rename or filter properties based on patterns.
Common issues
- Mapped types over unions distribute over each member, which may be surprising when working with union object types.
- Recursive mapped types require careful type alias declarations to avoid circularity errors.