Key Remapping (as)
Renaming keys dynamically during a mapped type loop.
Changing Keys on the Fly
In TypeScript 4.1+, you can change the actual name of a key while you are looping over it in a mapped type.
By using the as keyword inside the bracket notation, you can transform the key, format it, or even filter it out completely.
Getters, Setters, and Filtering
If you have a User type with { name: string; age: number }, and you want to generate a store object with { getName: () => string; getAge: () => number }, key remapping makes it trivial.
It allows you to derive highly complex, correctly typed APIs directly from simple base types.
Syntax
typescript
type User = { name: string; age: number };
// Add 'get' prefix, capitalize the original key, and return a function.
type Getters<T> = {
[K in keyof T as get${Capitalize<string & K>}]: () => T[K];
};
type UserGetters = Getters<User>;
// {
// getName: () => string;
// getAge: () => number;
// }
Try it
Watch the as keyword physically rename keys dynamically during a mapped type loop, converting plain properties into prefixed getter functions.
id: number;
name: string;
};
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Key remapping uses the syntax
[K in keyof T as NewKeyType]. - It is incredibly powerful when combined with Template Literal Types.
- Remapping a key to
neverremoves it from the final type. - It avoids the need for creating multiple boilerplate interfaces for getters/setters.
Done with this concept?
Mark it complete to track your progress. No login needed.