Fixed-shape results
Representing a function result with a fixed positional shape, such as a status value paired with a payload.
TypeScript · Function
Tuple types describe fixed-position arrays: each index can have a different type, and the tuple can also express optional or rest elements. Labels improve readability, while readonly prevents mutation.
A tuple type describes an array with a known number of elements and a specified type at each position. It can include optional elements, a final rest element for additional values, labels for readability, and a readonly modifier to prevent writes.
type Pair = [string, number];? after an element type to allow that position to be omitted.readonly before the tuple syntax when callers should not mutate its indexed elements.type UserRecord = readonly [id: number, name: string];
function formatUser(user: UserRecord): string {
return `${user[0]}: ${user[1]}`;
}
const user: UserRecord = [42, "Ada"];
console.log(formatUser(user));Defines a labeled, readonly tuple and reads each value using its position.
Representing a function result with a fixed positional shape, such as a status value paired with a payload.
Typing APIs where the first few arguments are fixed and later arguments share an array element type.
Passing immutable positional data between layers of a large codebase.
A tuple is an array type whose length and element types at particular positions are known. For example, [string, number] requires a string at index 0 and a number at index 1.
Follow-up: How do you model additional values after a fixed prefix? Use a rest element such as [string, ...number[]].
Optional tuple elements use ? after the element type, such as [string, number?]. An omitted optional element is represented in the type system as potentially absent.
Follow-up: Where may optional elements appear? An optional element must be followed only by optional elements.
Prefix the tuple with readonly, for example readonly [string, number]. The tuple remains useful for reading, but assignments to its properties are rejected.
Follow-up: When is readonly a good default? The documentation recommends it when tuples are created and generally left unmodified.
Array typesReadonlyArrayOptional tuple elementsRest elements in tuple typesLabeled tuple elements