Mapped Types
Mapped Types — the core idea
A mapped type traverses a union of keys to create a new object type. This is a compile-time transformation: no iteration or copied JavaScript object is generated. Common uses include readonly views, optional fields, and feature-flag representations.
What you’ll learn
- Explain 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: keyof Fields supplies two keys; the mapping changes each property's value type to boolean. The object literal provides the actual runtime values, which TypeScript checks against the mapped shape.
Keep the boundary clear: Mapped types transform type declarations, not existing objects. A mapping never auto-converts a numeric value into a boolean.
See the idea as a flow
Run the complete TypeScript example
Save the code as 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 Fields = { search: string; notifications: number };
type Enabled<T> = { [K in keyof T]: boolean };
const flags: Enabled<Fields> = { search: true, notifications: false };
console.log(flags.search);
console.log(flags.notifications);Verified output
true
falseBuild: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable mapped-types.ts; run: node 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
keyof Fields supplies two keys; the mapping changes each property's value type to boolean. The object literal provides the actual runtime values, which TypeScript checks against the mapped shape.
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
Mapped types transform type declarations, not existing objects. A mapping never auto-converts a numeric value into a boolean.
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
Create a numeric score type with the same keys using [K in keyof T]: number.
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
A mapped type traverses a union of keys to create a new object 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.