Types and inference

Use a tuple for fixed positions

Describe an array whose positions have known meanings and possibly different types.

An array type says every element looks the same. Sometimes that is wrong: a coordinate pair has exactly two numbers, and position matters. A tuple gives each position a known meaning and type:

type Point = [number, number]
const origin: Point = [0, 0]

TypeScript rejects missing positions, extra positions in the literal, and a string where a number belongs. Try const bad: Point = [0] and you get:

Type '[number]' is not assignable to type 'Point'.
  Source has 1 element(s) but target requires 2.

Reading also respects positions. origin[0] is a number, and origin[2] is an error because the tuple has no third element.

Tuples are still JavaScript arrays at runtime. The names and position rules exist only during checking. Array.isArray(origin) returns true, and the emitted JavaScript is a plain [0, 0].

Labeled positions

You can label positions for editor help:

type Point = [x: number, y: number]

Labels do not change the runtime value. It is still [0, 0]. But hovering over a function that accepts a Point now shows x and y instead of anonymous numbers, which makes call sites easier to read.

Tuples and destructuring

Tuples shine as return values, because destructuring gives the positions real names:

function divide(a: number, b: number): [result: number, remainder: number] {
  return [Math.floor(a / b), a % b]
}

const [result, remainder] = divide(17, 5)
// result: 4, remainder: 2

Both variables get the number type without any annotation. This convention is everywhere: React’s useState returns a [value, setter] tuple.

Tuple or object?

Use tuples for compact pairs and established return conventions. Use an object when readers benefit from names at the call site:

type Point = { x: number; y: number }

With three or more positions, point[2] tells the reader nothing, while point.z explains itself. My rule: two elements with an obvious order, tuple; anything more, object.

Exercise: write a function returning [value: string, found: boolean]. Destructure the result and inspect the inferred types.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →