AI Hints
Home›TypeScript Tutorial›Type Operators
TypeScript · Lesson 63 of 120

Mapped Types

Transform every key.

⏱ 2 min read▶ Video at 48:51🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

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.

Mapped Types
From the video: Mapped Types
  • 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.

keyvalue
[K in keyof T]each key
: booleannew type
?:make optional
readonlymake 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