typescript · level 2 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Unpack the pair. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const move: [string, number] = ["left", 3];
const [direction, steps] = move;
console.log(`Go ${direction} ${steps * 2} steps`);
your turn
Your turn. Fill in a high score table.
Add two rows to the table, each a name and a score. Then unpack each row into boxes called who and points.
fix it
This tuple has no third place. Fix it!
- Read the error:
TS2493: Tuple type '[number, number]' of length '2' has no element at index '2'. - Indexes start at 0, so a tuple of two has places 0 and 1. Both indexes on line 2 are one too big.
- Change
point[1]topoint[0]andpoint[2]topoint[1], then press run.
nailed it
you can pack values into tidy pairs. :D
- A tuple has a fixed length and a type for each place.
- The checker stops you reading past the end of a tuple.
- Destructuring unpacks a tuple into boxes in one line.
new words in your collection
- tuple
- destructuring
This lesson isn’t saved. A free account remembers every lesson you finish.