×

typescript · level 3 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Utility types are mapped types that come ready-made.

Some mapped types are so useful that TypeScript ships them built in. Each one is a : you give it a type in <> and get a new one back. makes every property optional, perfect for an update that changes only a few fields.

does the opposite and removes every ?. Readonly<Pet> adds readonly everywhere. Spread works on objects too: { ...pet, ...changes } copies the old object, then lays the changes on top.

interface Pet {
  name: string;
  age: number;
  toy?: string;
}
function update(pet: Pet, changes: Partial<Pet>): Pet {
  return { ...pet, ...changes };
}
const rex: Pet = { name: "Rex", age: 4 };
const older = update(rex, { age: 5 });
const full: Required<Pet> = { ...older, toy: "ball" };
console.log(older, full.toy);

When two spread objects share a key, the one written last wins.