Lessons · TypeScript · a fixed-length, fixed-type array
A fixed shape of array
[string, number] is a tuple: exactly two items, a string at position 0 and a number at position 1. Each position has its own type.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
A pair returned from a function, a coordinate, a key-value entry: small fixed groups where an array's 'any length of one type' says too little.
How to think about it
Use a tuple when the positions mean different things and the length is fixed. Destructure it to give the positions names; beyond three items, an object with named fields reads better.
Worked example
const pair: [string, number] = ["a", 1];Fixed length, a type per position.
const swapped: [string, number] = [1, "a"];Error: the positions are swapped.
const [label, count] = pair;Destructuring keeps each position's type.
console.log(label.toUpperCase(), count + 1);A 2.
Your turn
A point with two numbers.
const point: [number, ] = [3, 4];
Solve one with the compiler running
The trap
A tuple is still an array at runtime, and push adds a third item without complaint. readonly [string, number] freezes it.