Arrays and Tuples
A project holds a list of task titles, and it could be three titles or three hundred. Elsewhere you pass around a pair — a task's id and its title. Both are JavaScript arrays at runtime, but TypeScript describes them differently, because they mean different things.
The rule
Array: any length, one element type. Tuple: fixed length, a type per position.
Arrays have two equivalent spellings:
let titles: string[] = ["Buy milk", "Call Sam"];
let ids: Array<number> = [1, 2, 3];
titles.push("Pay rent"); // fine
titles.push(42); // error: 42 is not a string
const first = titles[0]; // stringEvery element shares the one element type, and the length can change freely. Want an array nobody can modify? Use readonly string[] (or ReadonlyArray<string>), and methods like push disappear from the type.
Tuples fix the number of elements and give each position its own type:
let entry: [number, string] = [7, "Buy milk"];
entry[0]; // number
entry[1]; // string
entry = ["Buy milk", 7]; // error: the positions are swapped
entry[2]; // error: the tuple has no index 2Tuples can also name their positions for readability, [id: number, title: string], and mark trailing positions optional with ?, as in [number, string, boolean?]. A well-known example is React's useState, which returns a tuple: the current value and a function to change it.
Remember that inference produces arrays, not tuples: let pair = [7, "Buy milk"] is inferred as an array whose elements are each a number or a string. If you want a tuple, annotate it (or use as const, covered later).
The shortcut
Ask "Does each position mean something different?"
- No, they are all the same kind of thing (titles, ids, tasks) → array:
T[]. - Yes, position 0 is one thing and position 1 another → tuple:
[A, B]. - More than about three positions → use an object with named properties instead.
All the tasks in a project
Every element is a Task and the count varies, so
Task[].
The trap is using a tuple where an object would be clearer. row[3] tells a reader nothing; row.due tells them everything.
Drills
Answer fast — trust the rule.
Which two annotations mean the same thing?
What is the type of pair[1] if pair: [number, string]?
Which value fits the type [number, string]?
How do you type a list of any number of id-title pairs?
Remember
- Array: any length, one element type. Tuple: fixed length, a type per position.
- Ask "does each position mean something different?" — yes means tuple.
- Trap: long tuples are hard to read; switch to an object with named fields.
