Skip to the workspace
Pebellslearn by building
TypeScript Types  ›  Lesson

Arrays and Tuples

Array 12 minAn array type describes a collection of elements. A tuple type describes individual positions and can also include optional or rest elements.

typescript / Arrays and Tuples

Explore each scene at your own pace.

01 · The rule

The rule

Arrays and Tuples

An array type describes a collection of elements. A tuple type describes individual positions and can also include optional or rest elements.

Choose between a variable-length collection and a tuple with positional meaning.

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];   // string

Every 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 2

Tuples 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).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.