TypeScript
/Advanced
Mapped Types
Definition
A way to create a new type by iterating (mapping) over the keys of an existing type and applying a transformation.
Explain Like I'm New
A Mapped Type is like a factory assembly line. It takes an existing Interface, puts it on the conveyor belt, loops through every single property, performs an action (like making them all Optional, or turning them all into Booleans), and outputs a brand new Interface.
Real World Example
Creating a type for a form's 'validation errors'. If the original `User` has `{ name: string, age: number }`, the mapped `UserErrors` type automatically generates `{ name?: string, age?: string }` to hold error messages.
Common Use Cases
- •Building generic Utility Types (Partial, Readonly)
- •State management validation
Interactive Example
interface User { name: string; age: number; } // The Mapped Type Factory: // 1. Loops through all keys of T // 2. Assigns boolean as the new value for every key type Booleanify<T> = { [K in keyof T]: boolean; }; // We pass User into the factory type UserValidationMap = Booleanify<User>; /* Resulting Type: { name: boolean; age: boolean; } */ const isValid: UserValidationMap = { name: true, age: false };
Interview Questions
basic
- What does the `[K in keyof T]` syntax do?
intermediate
- How do you use mapped types to make all properties readonly?
advanced
- What is Key Remapping using the `as` keyword in mapped types?