Advanced TypeScript
Mapped Types
Mapped types transform object types by iterating over keys. They are how TypeScript expresses mechanical object-shape changes such as readonly, optional, required, picked, omitted, and remapped properties.
- Mapped types iterate over keys
- Indexed access gets property value types
- Modifiers can be added or removed
- Keys can be remapped
- Mechanical transformation is not semantic design
type Mutable<T> = {
-readonly [K in keyof T]: T[K]
}
type Nullable<T> = {
[K in keyof T]: T[K] | null
}type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
}
type UserGetters = Getters<{ id: string; name: string }>
// { getId: () => string; getName: () => string }| Tool | Use |
|---|---|
| keyof T | Get key union |
| K in keyof T | Iterate keys |
| T[K] | Read property value type |
| readonly / -readonly | Add/remove readonly |
| ? / -? | Add/remove optional |
| as | Remap/filter keys |