TypeScript · Lesson 63 of 120
Mapped Types
Transform every key.
A mapped type loops over the keys of a type, and builds a new type from them. It's how many built in helpers work.

- Loop over keys
- Build a new type
- Built-in helpers
Flags for every field
Flags of T maps every key of T to a boolean. For a bike, that gives a boolean for model, price, and stock. Perfect for tracking which fields were changed. Run it.
app.tstypescript
type Bike = { model: string; price: number; stock: number };
type Flags<T> = {
[K in keyof T]: boolean;
};
const changed: Flags<Bike> = { model: false, price: true, stock: false };
const names = Object.entries(changed).filter(([, v]) => v).map(([k]) => k);
console.log("Changed fields:", names);Output
Changed fields: [ 'price' ]
Reading the syntax
K in keyof T means for each key K. After the colon comes the new type for that key. You can also add question marks, or readonly, to every key at once.
| key | value |
|---|---|
| [K in keyof T] | each key |
| : boolean | new type |
| ?: | make optional |
| readonly | make readonly |
Summary
Mapped types build a new type by transforming every key. Next, Partial and Required.
Key takeaways- [K in keyof T]
- New type per key
- Built-ins use it
Next up: Partial and Required — optional or not