Sub topic 7
When to use a tuple and when to use an array
This chapter assumes you know how to annotate arrays with T[], you have seen tuple syntax such as [number, string], and you are comfortable with union types. Its goal is to give you a way to choose between the two types. It also covers what goes wrong when you choose badly.
The core distinction
An array type describes a list of any length whose elements share one type, or one union of types. A tuple type describes a list of known length where each position has its own type.
const scores: number[] = [90, 85, 72]; // any length, every element is a number
const entry: [string, number] = ["Ada", 36]; // exactly two elements, string then numberPosition carries meaning in a tuple. In an array, position usually carries no meaning, and the elements are interchangeable. Most decisions follow from that.
Decision criteria
| Question | Points to an array | Points to a tuple |
|---|---|---|
| Is the length known at compile time? | No, it grows or shrinks | Yes, it is fixed |
| Are the elements the same kind of thing? | Yes, all are scores, names or lines | No, each position means something different |
| Does position carry meaning? | No, you loop over all elements | Yes, index 0 is the key and index 1 is the value |
| Will you iterate with `map`, `filter` or `reduce`? | Yes | Rarely |
| Is it a short, local grouping? | Not necessarily | Yes, two or three elements |
If you answer "array" to the first three rows, use an array. If you answer "tuple" to most rows, a tuple is a good fit.
Good uses of tuples
Short fixed-size values
Coordinates, ranges and pairs are natural tuples. Both elements have the same type here, but the length of exactly two is part of the contract.
type Point = [number, number];
function distance(a: Point, b: Point): number {
return Math.hypot(a[0] - b[0], a[1] - b[1]);
}
console.log(distance([0, 0], [3, 4])); // 5A number[] would accept [1] or [1, 2, 3]. The tuple rejects both at compile time.
Returning several values
A function that returns two or three related values can return a tuple. The caller then picks its own names through destructuring.
function parseKeyValue(line: string): [key: string, value: string] {
const index = line.indexOf("=");
if (index === -1) {
return [line, ""];
}
return [line.slice(0, index), line.slice(index + 1)];
}
const [key, value] = parseKeyValue("host=localhost");
console.log(key, value); // host localhostReact's useState and the standard library's Object.entries use the same pattern. Object.entries returns an array of [string, T] tuples, which is a good combination: an array of tuples.
Arrays of tuples
An array and a tuple often nest. The list has an arbitrary length, and each item has a fixed shape.
const prices: [item: string, cents: number][] = [
["coffee", 350],
["tea", 280],
];
const total = prices.reduce((sum, [, cents]) => sum + cents, 0);
console.log(total); // 630
const lookup = new Map<string, number>(prices);
console.log(lookup.get("tea")); // 280The Map constructor accepts an iterable of [key, value] pairs, so the tuple type fits it directly.
Good uses of arrays
Use an array when the list is a collection: users, lines of a file, search results. You do not know the length ahead of time, and the code treats all elements the same way.
function longest(words: readonly string[]): string {
return words.reduce((best, w) => (w.length > best.length ? w : best), "");
}Do not use a tuple for this, even if a test happens to pass three strings. The tuple type would force every caller to supply exactly three. If you notice yourself writing [string, string, string] for a list that could grow, change it to string[].
When a tuple is the wrong tool
Too many positions
Tuples have no field names unless you add labels. At four or five elements, callers must remember what index 3 means, and the type does not help them.
type UserTuple = [string, string, number, boolean];
type User = {
name: string;
email: string;
age: number;
active: boolean;
};
const u: User = { name: "Ada", email: "[email protected]", age: 36, active: true };With the object, u.active documents itself. With the tuple, t[3] does not. Labels such as [name: string, email: string] improve editor hints, but they do not change how callers read or write the value. A common rule of thumb is to switch to an object type at about three elements.
Values that change in shape
Tuples are poor for data that gets new fields over time. Adding a position at the end of a tuple is usually compatible, but inserting one in the middle breaks every caller that destructures by position. Adding a property to an object type breaks no one.
Public APIs you expect to evolve
Returning [result, error] from a library function locks in that order. An object such as { result, error } lets you add warnings later.
The inference gotcha
TypeScript does not guess that you want a tuple. An array literal is inferred as an array unless the context says otherwise.
type Point = [number, number];
function distance(a: Point, b: Point): number {
return Math.hypot(a[0] - b[0], a[1] - b[1]);
}
const origin = [0, 0]; // number[]
// distance(origin, [3, 4]);
// Error: Argument of type 'number[]' is not assignable to parameter of type 'Point'.
const origin2: Point = [0, 0]; // fix 1: annotate the declaration
const origin3 = [0, 0] as const; // fix 2: readonly [0, 0]
distance(origin2, [3, 4]); // 5The error appears because the type of origin was fixed when it was declared, and number[] does not carry its length. When the literal is written directly in the argument position, as in [3, 4], the parameter type provides context and the literal is checked as a tuple.
The as const fix has a catch. It produces a readonly tuple, and a readonly tuple is not assignable to a mutable Point. The call distance(origin3, [3, 4]) would fail unless the parameters are declared readonly [number, number]. For library-style functions that only read their input, declare the parameters as readonly. Then both forms work.
type ReadonlyPoint = readonly [number, number];
function norm(p: ReadonlyPoint): number {
return Math.hypot(p[0], p[1]);
}
const a: [number, number] = [3, 4];
const b = [3, 4] as const;
console.log(norm(a), norm(b)); // 5 5A mutable tuple is assignable to a readonly one, but not the other way around.
Failure modes to watch for
- Mutation methods are not length-checked. A mutable
[number, string]still haspush, andt.push(3)compiles. The tuple's declared length can then be wrong at runtime. Preferreadonlytuples when the value should not change. - Choosing a tuple to avoid writing a type name. If you find yourself writing the same
[string, number, boolean]in several places, either give it an alias or use an object type. - Using
T[]for fixed-shape data. A function that takesstring[]for a[host, port]pair will happily accept an empty array. The failure shows up at runtime asundefined. - Assuming destructuring is checked for arrays. With
number[],const [a, b] = listgivesaandbthe typenumber, even when the list is empty. Turn onnoUncheckedIndexedAccessif you want those elements typednumber | undefined. With a tuple, destructuring past the end is a compile error.
const list: number[] = [];
const [first] = list; // first: number, but undefined at runtime without the flag
const pair: [number, number] = [1, 2];
// const [x, y, z] = pair; // Error: Tuple type '[number, number]' of length '2' has no element at index '2'.Summary of the choice
- Use
T[]for collections of the same kind of thing with unknown length. - Use a tuple for two or three values where position has a clear meaning, especially return values and pairs.
- Use an object type once there are more than about three fields, or when the shape may grow.
- Use
readonlyon both arrays and tuples that you only read.
Exercise
A function getBounds(values: number[]) returns the smallest and largest value. Another function getStats(values: number[]) returns the minimum, maximum, mean, median and count. Which return type would you pick for each: an array, a tuple or an object type? Give one reason for each.
Show answer
For getBounds, a tuple [min: number, max: number] fits, because the length is exactly two, each position has a distinct meaning, and callers can destructure it as const [lo, hi] = getBounds(xs). A number[] would hide the length. For getStats, use an object type such as { min: number; max: number; mean: number; median: number; count: number }. With five values of mixed meaning, callers would struggle to remember positions in a tuple, and an object lets you add fields later without breaking existing callers.
Exercise
Why does distance(origin, [3, 4]) fail when const origin = [0, 0]; and distance takes two [number, number] parameters? Give two ways to fix the declaration.
Show answer
The declaration infers origin as number[], which has no fixed length and is not assignable to [number, number]. The first fix is to annotate it: const origin: [number, number] = [0, 0];. The second is to use as const, which gives readonly [0, 0], but then the parameter type must also be readonly (readonly [number, number]), because a readonly tuple is not assignable to a mutable one.