Concept Flow - Basic mapped type syntax
Start with Keys
Iterate over Keys
Apply Transformation
Build New Type
Resulting Mapped Type
Mapped types take each key from an existing type and create a new type by applying a transformation to each key.
type Options = {
width: number;
height: number;
};
type ReadonlyOptions = {
readonly [K in keyof Options]: Options[K];
};| Step | Action | Key (K) | Original Type (Options[K]) | Mapped Property | Resulting Property Type |
|---|---|---|---|---|---|
| 1 | Start mapping | ||||
| 2 | Iterate key | width | number | readonly width | number |
| 3 | Iterate key | height | number | readonly height | number |
| 4 | Finish mapping | ReadonlyOptions type created |
| Variable | Start | After 1 | After 2 | Final |
|---|---|---|---|---|
| K | undefined | width | height | all keys processed |
| Mapped Property | none | readonly width | readonly height | readonly width, readonly height |
| Resulting Type | none | { readonly width: number } | { readonly width: number; readonly height: number } | ReadonlyOptions |
Mapped types syntax:
type NewType = { [K in keyof OldType]: OldType[K] };
Use 'in keyof' to loop keys.
Add modifiers like 'readonly' to change properties.
Creates new types by transforming existing ones.