Key Remapping in Mapped Types
Key Remapping in Mapped Types — the core idea
The as clause remaps keys inside a mapped type. Template literal types can create a family of methods from data property names. The result is only a type; the programmer must still implement each runtime method.
What you’ll learn
- Explain key remapping in mapped types with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: string & K makes each property name compatible with a string template. Capitalize forms Views and Clicks, and as produces getViews and getClicks signatures. Implementations are supplied explicitly.
Keep the boundary clear: Key remapping does not add real methods to a Metrics object. Calling a method still requires an object containing that function.
See the idea as a flow
Run the complete TypeScript example
Save the code as key-remapping-mapped-types.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
type Metrics = { views: number; clicks: number };
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
const stats: Getters<Metrics> = { getViews: () => 120, getClicks: () => 7 };
console.log(stats.getViews());
console.log(stats.getClicks());Verified output
120
7Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable key-remapping-mapped-types.ts; run: node key-remapping-mapped-types.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
string & K makes each property name compatible with a string template. Capitalize forms Views and Clicks, and as produces getViews and getClicks signatures. Implementations are supplied explicitly.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
Key remapping does not add real methods to a Metrics object. Calling a method still requires an object containing that function.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Extend Metrics with shares:number and implement getShares to satisfy the mapped type.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
The as clause remaps keys inside a mapped type.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.