×

typescript · level 3 · unit 1 · lesson 2

  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

A tells a generic what it can count on.

A generic like <T> works with any type. That is powerful, but it means TypeScript knows nothing about T. Ask for item.name and the checker stops you with TS2339, because not every type has a name.

A constraint fixes that. Write <T extends { name: string }> and T can be any type, so long as it has a name that is a string. Inside the function you may use .name, and callers still get their own full type back, extra properties and all.

Pass something without a name and the checker refuses it with TS2345.

function longestName<T extends { name: string }>(items: T[]): T {
  let best: T = items[0];
  for (const item of items) {
    if (item.name.length > best.name.length) {
      best = item;
    }
  }
  return best;
}
const pets = [{ name: "Rex", legs: 4 }, { name: "Tibbles", legs: 4 }];
const winner = longestName(pets);
console.log(winner.name, winner.legs);

Read extends in a constraint as “must at least have”.