Mapped Types and Key Remapping
Mapped types iterate over keys in a type and produce a new type. The basic pattern is { [K in keyof T]: ... }. You can add or remove modifiers and, in modern TypeScript, remap keys with as. Mapped types power many utility types and can model transformations such as making every field nullable or generating event names.
Use mapped types when the transformation is systematic. For a simple domain contract, an explicitly written type may be easier to maintain. Complex recursive or conditional mapped types can create slow type checking and difficult error messages.
Make every property a getter signature
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
type User = { name: string; age: number };
type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number }💡 The mapped type iterates over the keys of
T, remaps each key using a template literal type, and returns a function producing the original property type.Key Takeaways
- Mapped types transform keys systematically.
- Key remapping uses
asin a mapped type. - Keep advanced type transformations readable and purposeful.
Knowledge Check
Which syntax iterates over the keys of T in a mapped type?