×

typescript · level 2 · unit 4 · 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

A is a short array where every place has its own type.

Some values always travel together in a fixed order: a name and a score, or a width and a height. A tuple is an array with a fixed length and a type for each place: [string, number].

The checker knows exactly what sits where. best[0] is a string and best[1] a number. Ask for best[2] and you get TS2493, because there is no third place.

unpacks a tuple into boxes in one go: const [name, score] = best; makes two boxes, filled in order.

const best: [string, number] = ["Ava", 98];
console.log(best[0], best[1]);
const [name, score] = best;
console.log(`${name} scored ${score}.`);
const table: [string, number][] = [["Ava", 98], ["Ben", 87]];
for (const [player, points] of table) {
  console.log(player, points);
}

Destructuring works in a for...of too, so each lap unpacks one tuple.