Tuples
A tuple is an array type with a fixed length and a type for each position, written [string, number]. Index 0 and index 1 are different types, unlike a normal array.
Detailed Explanation
A string[] is a list of strings of any length. A [string, number] is a pair: first a string, then a number, and then nothing else. The compiler tracks both the element types and the length. pair[0] is a string. pair[1] is a number. pair[2] is an error (or undefined under noUncheckedIndexedAccess, still not a useful read).
Tuples exist because some values are ordered slots, not homogeneous lists. A useState return is a tuple. A map entry from Map.prototype.entries is a tuple. A CSV row with a known schema is a tuple. Coordinates, ranges, and [error, result] callbacks are tuples.
You can label slots for readers: [start: Date, end: Date]. Labels do not exist at runtime and do not affect assignability. They show up in autocomplete and in editor hovers.
Optional slots use ?: [string, number?]. Rest slots use ...: [string, ...number[]] is a string followed by any number of numbers. readonly [string, number] removes mutating methods and index assignment, the same idea as readonly T[].
Assignability is stricter than for arrays. [string, number] is not assignable to [string] (extra element) in most positions, and [string] is not assignable to [string, number] (missing element). A tuple is assignable to a matching array type: [string, string] may be passed where string[] is expected, because every element is a string. The reverse is not safe and is rejected: a string[] might have the wrong length.
Open-ended tuples and array types meet at .... [...T[], U] and [U, ...T[]] are how you type "a non-empty list" or "a head plus a tail." Those forms are the type-level version of rest and spread.
The usual mistake is using a tuple when the length is not part of the meaning. A list of tags is string[]. A pair of latitude and longitude is [number, number] or, often better, { lat: number; lng: number }. Named properties survive reordering; tuple slots do not. Reach for a tuple when order is the API, and for an object when names are the API.
Code Examples
1. Position types, length, and labels.
// 1. Position types, length, and labels.
type Range = [start: number, end: number];
function width(range: Range): number {
return range[1] - range[0];
}
width([10, 25]); // 15
// width([10]);
// Error: Source has 1 element(s) but target requires 2.2. Optional and rest elements.
// 2. Optional and rest elements.
type HeadAndTail = [string, ...number[]];
const row: HeadAndTail = ["score", 1, 2, 3];
const name = row[0]; // string
const firstScore = row[1]; // number | undefined if noUncheckedIndexedAccess, else number3. Tuples as function returns, and why objects sometimes win.
// 3. Tuples as function returns, and why objects sometimes win.
function splitEmail(email: string): [local: string, domain: string] {
const at = email.indexOf("@");
return [email.slice(0, at), email.slice(at + 1)];
}
const [local, domain] = splitEmail("ada@example.com");
console.log(local, domain); // ada example.com
type LatLng = { lat: number; lng: number };
const city: LatLng = { lat: 12.97, lng: 77.59 };Common Gotchas
`[string, number]` is not `(string | number)[]`
the union array allows any mix and any length. The tuple does not.
Extra properties vs extra elements
object excess-property checks apply to fresh literals; tuple length checks always apply. Do not expect them to behave the same.
`typeof` a tuple value is still `"object"`
there is no runtime tuple. `Array.isArray` is true. Labels and length exist only in the type.
Mutable tuples share array covariance holes
a `[Dog]` assigned to `[Animal]` can have a `Cat` written into it through the wider view. Prefer `readonly [Dog]`.