Sub topic 6
Tuples: fixed length, typed positions
This chapter assumes you know JavaScript arrays and their methods, basic TypeScript annotations, and union types. You should also have read the earlier chapters on T[] and Array<T>, inference of array literals, and readonly arrays.
What a tuple is
An array type such as number[] describes a list of any length where every element has the same type. A tuple type describes a list whose length is fixed and whose element type is set separately for each position.
const entry: [string, number] = ["apples", 3];
const name = entry[0]; // string
const count = entry[1]; // number
console.log(name.toUpperCase(), count.toFixed(1)); // APPLES 3.0
console.log(entry.length); // 2The annotation [string, number] says three things:
- The value has exactly two elements.
- Position 0 holds a
string. - Position 1 holds a
number.
When you read entry[0], TypeScript knows the type is string, not string | number. That precision is the reason to use a tuple.
Tuples are plain arrays at runtime
Tuples exist only in the type system. After compilation, ["apples", 3] is an ordinary JavaScript array. Array.isArray(entry) returns true, and nothing checks the length while the program runs. All the guarantees come from the compiler, so they hold only for code that TypeScript has checked. Data from JSON.parse, a network response, or an any value can break them without any error.
What the compiler checks
The compiler checks length, order, and the type at each position.
const ok: [string, number] = ["apples", 3];
// Each line below is a compile error:
// const tooShort: [string, number] = ["apples"];
// Type '[string]' is not assignable to type '[string, number]'.
// Source has 1 element(s) but target requires 2.
// const tooLong: [string, number] = ["apples", 3, true];
// Source has 3 element(s) but target allows only 2.
// const wrongOrder: [string, number] = [3, "apples"];
// Type 'number' is not assignable to type 'string'.Reading a position that does not exist is also an error when the index is a literal:
const entry: [string, number] = ["apples", 3];
// entry[2];
// Error: Tuple type '[string, number]' of length '2' has no element at index '2'.
const length = entry.length; // type is the literal 2, not numberFor a plain array, arr[5] compiles even if the array is empty. A tuple turns that mistake into a compile-time error. Its length property is also typed as the literal 2, so a comparison such as entry.length === 3 is flagged as a comparison with no overlap.
Elements can be any type: unions, objects, functions, or other tuples. An empty tuple [] is also valid. It allows only an empty array.
type Cell = [row: number, col: number]; // labeled elements are covered in a later chapter
type Reading = [timestamp: Date, value: number | null];
const nested: [string, [number, number]] = ["origin", [0, 0]];
const inner = nested[1][0]; // numberTuples are not inferred from literals
By default, an array literal is inferred as an array, not a tuple. This surprises many people.
const inferred = ["apples", 3]; // (string | number)[]
function lookup(id: number) {
return ["Ada", true]; // return type is inferred as (string | boolean)[]
}
const user = lookup(1);
const flag = user[1]; // string | boolean, not booleanTypeScript assumes an array literal may later grow, shrink, or be reordered, so it picks the safer array type. To get a tuple, give the compiler a tuple type to check against. The usual places are a variable annotation, a parameter, or a return type.
function lookupTyped(id: number): [string, boolean] {
return ["Ada", id > 0];
}
const [who, active] = lookupTyped(1); // who: string, active: boolean
console.log(who, active);Once the return type is annotated, the literal ["Ada", id > 0] is checked against [string, boolean] and accepted. The caller gets the exact types. The as const approach to getting a tuple from a literal has its own chapter later.
Tuples and arrays are related, in one direction
A tuple is assignable to an array type that covers all of its element types. The reverse is not true, because an array could have any length.
const entry: [string, number] = ["apples", 3];
const asArray: (string | number)[] = entry; // ok
// const back: [string, number] = asArray;
// Error: Target requires 2 element(s) but source may have fewer.
const nums: number[] = [1, 2];
// const point: [number, number] = nums;
// Error: Target requires 2 element(s) but source may have fewer.The second error shows that a tuple does not accept a number[], even when you know it holds two numbers. TypeScript cannot see the length of an array type. To convert, you need a runtime check or an explicit assertion. An assertion such as nums as [number, number] is allowed, but it moves the responsibility for correctness to you.
Tuples also inherit the array methods, and those methods lose the positional information. entry.map(...) and entry.filter(...) return ordinary arrays, and entry.slice(0, 1) returns (string | number)[]. If you transform a tuple and want a tuple back, you must build it yourself:
const entry: [string, number] = ["apples", 3];
const doubled = entry.map((x) => x); // (string | number)[]
const renamed: [string, number] = [entry[0].toUpperCase(), entry[1] * 2];
console.log(doubled, renamed); // [ 'apples', 3 ] [ 'APPLES', 6 ]Indexing with a non-literal number
A literal index gives the type at that position. An index typed as plain number gives the union of all positions, because the compiler cannot know which one you mean.
const entry: [string, number] = ["apples", 3];
function at(i: number) {
return entry[i]; // string | number
}
const literal = entry[0]; // string
console.log(at(1), literal);This also applies in a loop with a numeric counter. If you need each element's own type, access the positions by literal index or use destructuring (next chapters).
Where tuples show up in real code
Tuples are common in the standard library and in frameworks:
Object.entries(obj)returns[string, T][], an array of key and value pairs.new Map<string, number>([["a", 1], ["b", 2]])takes an iterable of[string, number]tuples.- Hook-style functions return a small, fixed list of values, such as a value and a setter.
function useToggle(initial: boolean): [boolean, () => void] {
let value = initial;
const toggle = () => {
value = !value;
};
return [value, toggle];
}
const [isOn, toggle] = useToggle(false);
toggle();
console.log(isOn); // false: the returned value is a snapshotThe example also shows a design point. The tuple carries a snapshot of value, not a live view. This is a behavior of the code, not of the tuple type.
Choosing between a tuple and an array
Use a tuple when position carries meaning and the length is known. Use an array when the list is a collection of similar items that can grow or shrink.
| Situation | Better choice | Reason |
|---|---|---|
| A list of user names read from a file | `string[]` | Same kind of item, unknown length |
| A 2D coordinate | `[number, number]` | Two values, position means x and y |
| A function returning a result and a status | `[Result, Status]` | Two different types in fixed order |
| Rows from a database query | `Row[]` | Many items of one shape |
| A key and value pair | `[string, number]` | Fixed pair, as in `Map` entries |
Tuples have limits. A tuple with more than three or four positions is hard to read, and callers must remember what each position means. If the values have names that matter, such as { x: number; y: number }, an object type is usually clearer. Labeled tuple elements, covered later, soften this problem. A tuple is a good choice for short, local, and obvious groupings.
Common mistakes
- Expecting inference to produce a tuple. An unannotated literal is an array. Annotate the variable, parameter, or return type.
- Assigning an array to a tuple. The compiler rejects it because the length is unknown. Check the length at runtime, or build the tuple explicitly.
- Trusting tuple types for external data. Types vanish at runtime. A parsed JSON array typed as
[string, number]is only a claim, so validate it. - Assuming methods preserve the shape.
map,filter,slice, andconcatall return plain arrays. - Assuming the length is always enforced. Mutating methods like
pushcan still change a mutable tuple without a compile error. The pitfalls chapter covers this and how readonly tuples prevent it.
Exercise
What are the types of a, b and c in this code, and which line, if any, is a compile error?
const p: [string, number] = ["x", 1];
const a = p[0];
const b = p[2];
const c = p.map((v) => v);
Show answer
a is string, because index 0 is a literal and the tuple has string at that position. The line const b = p[2]; is a compile error: the tuple type has length 2 and no element at index 2, so b gets no useful type. c is (string | number)[], because map returns an ordinary array and drops the positional types.
Exercise
A function is written as function split(n: number) { return [Math.floor(n), n % 1]; }. A caller writes const parts: [number, number] = split(2.5); and gets an error. Why, and what is the smallest fix?
Show answer
Without an annotation the return value is inferred as number[], and a number[] cannot be assigned to [number, number] because its length is unknown. The smallest fix is to annotate the return type: function split(n: number): [number, number] { return [Math.floor(n), n % 1]; }.