Sub topic 12
Tuple pitfalls: push and out-of-range access
This chapter assumes you know how to write tuple types such as [number, string], how to destructure them, and how readonly and as const work on arrays. It covers two places where a tuple's fixed length is weaker than it looks. The first is mutating methods like push. The second is reading an index that does not exist.
A tuple is still an array
A tuple type like [number, string] is a subtype of Array<number | string>. TypeScript tracks the length and per-position types for reads and assignments. A tuple also inherits every method from Array, and those methods are typed for a plain array.
That inheritance is the source of most tuple surprises. Operations that read by a literal index are checked against the tuple's shape. Operations that go through array methods are checked against the array's shape.
Pitfall 1: push on a mutable tuple
const t: [number, string] = [1, "a"];
t.push(3); // compiles
console.log(t.length); // 3
console.log(t); // [ 1, 'a', 3 ]
// t[2]; // Error: Tuple type '[number, string]' of length '2' has no element at index '2'.push is declared on Array<T> as accepting T values, where T is number | string here. The compiler does not change the tuple's type after the call. At runtime t has three elements, but its type still says it has two.
The same applies to the other methods that change length:
popandshiftremove elements. Their return type includesundefined, so the compiler does not claim the removed value is anumberor astring.unshiftandspliceinsert or remove elements and are not checked against the tuple's length.
The type of t.length stays the literal 2, so TypeScript will reject a check like t.length === 3 as a comparison with no overlap. The runtime value can still be 3. The compiler cannot see the mismatch, and that is the failure mode to remember.
Aliasing hides the problem
A tuple is assignable to an array type with a compatible element type. Once it is passed that way, the receiving function can change its length.
function addExtra(list: number[]): void {
list.push(99);
}
const point: [number, number] = [1, 2];
addExtra(point); // compiles: [number, number] is assignable to number[]
console.log(point); // [ 1, 2, 99 ]No cast is involved, and the compiler reports nothing. A function you did not write can break an invariant that you declared.
The fix: readonly
A readonly tuple has no mutating methods in its type. It is also not assignable to a mutable array type, so aliasing is caught at the call site.
function addExtra(list: number[]): void {
list.push(99);
}
function total(list: readonly number[]): number {
return list.reduce((sum, n) => sum + n, 0);
}
const point: readonly [number, number] = [1, 2];
// point.push(3); // Error: Property 'push' does not exist on type 'readonly [number, number]'.
// addExtra(point); // Error: The type 'readonly [number, number]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.
console.log(total(point)); // 3Use readonly for any tuple that represents a fixed record, such as a coordinate pair or a [key, value] entry. Use readonly parameter types in functions that only read their input. A readonly number[] parameter accepts both mutable and readonly arguments, so the stricter parameter type costs callers nothing.
Pitfall 2: out-of-range access
TypeScript checks index reads on tuples, but only when it can see the index.
const t: [number, string] = [1, "a"];
const first = t[0]; // number
const second = t[1]; // string
// const third = t[2]; // Error: Tuple type '[number, string]' of length '2' has no element at index '2'.
// Destructuring is checked the same way:
// const [a, b, c] = t; // Error: Tuple type '[number, string]' of length '2' has no element at index '2'.A literal index (t[2]) and a destructuring pattern both have a known position, so the compiler compares it to the tuple's length. The error shows up where you wrote the bad access.
Non-literal indexes are not checked against the length
When the index is a variable of type number, TypeScript cannot know which element you mean. It returns the union of all element types.
const t: [number, string] = [1, "a"];
function at(i: number): number | string {
return t[i]; // no error: type is string | number
}
console.log(at(0)); // 1
console.log(at(5)); // undefined at runtime, but typed as number | stringat(5) returns undefined at runtime, while the declared return type says number | string. This is the same gap that exists for plain arrays.
With noUncheckedIndexedAccess enabled in tsconfig.json, reads with a non-literal index include undefined. The function above would then fail to compile until you handle that case.
const t: [number, string] = [1, "a"];
function at(i: number): number | string | undefined {
return t[i]; // with noUncheckedIndexedAccess, the type includes undefined
}
const value = at(5);
if (value !== undefined) {
console.log(value);
} else {
console.log("no element at that index");
}Literal-index reads such as t[0] stay precise with the flag on, because the compiler knows the element exists.
Optional and rest elements change the rules
Which indexes are legal depends on how the tuple is declared.
type Range = [start: number, end?: number];
type Row = [id: number, ...tags: string[]];
const r: Range = [0];
const end = r[1]; // number | undefined: the position may be absent
const row: Row = [1, "new"];
const tag = row[5]; // string: a rest element makes any later index legal
console.log(end, tag); // undefined undefinedFor Range, index 1 is allowed, and its type includes undefined because the element is optional. Index 2 is an error. For Row, every index from 1 onward is legal, because ...tags: string[] has no fixed end. The read row[5] is typed string and is undefined at runtime, which is the same gap as with a plain array.
How the checks fit together
Summary of behavior
| Operation | `[number, string]` | `readonly [number, string]` | Column | Column |
|---|---|---|---|---|
| `t[0]` | `number` | `number` | ||
| `t[2]` (literal) | Error | Error | ||
| `const [a, b, c] = t` | Error | Error | ||
| `t[i]`, `i: number` | `string \ | number` | `string \ | number` |
| `t.push(3)` | Compiles, length not tracked | Error: no such method | ||
| Pass to `number[]` parameter (all-number tuple) | Allowed | Error |
Practical guidance
- Declare tuples that should not change as
readonly, or create them withas const. - Take
readonlyarray or tuple types in function parameters when the function only reads. - Treat the type of
t.lengthas a hint, not a guarantee, on any mutable tuple. - Turn on
noUncheckedIndexedAccessif your code reads with computed indexes. Handle theundefinedcase in the code that reads. - If a function must return a new, longer value, build a new tuple with a spread, as in
[...t, 3], instead of callingpush. The result type is then[number, string, number], and the original is untouched.
const t: readonly [number, string] = [1, "a"];
const longer = [...t, 3] as const; // readonly [number, string, 3]
console.log(longer); // [ 1, 'a', 3 ]Exercise
Given const pair: [string, number] = ["x", 1];, which of these lines produce a compile error, and what does pair.length hold at runtime after the valid ones run? (1) pair.push(2); (2) const z = pair[2]; (3) const [a, b, c] = pair;
Show answer
Line (1) compiles, because push is typed for Array<string | number> and does not check the tuple length. Lines (2) and (3) both fail with "Tuple type '[string, number]' of length '2' has no element at index '2'". After line (1) runs, pair.length is 3 at runtime, although the compiler still types it as 2.
Exercise
A function function scale(v: number[]): void multiplies each element in place. A teammate calls it with const origin: [number, number] = [0, 0];, and later someone adds v.push(1) inside scale. How can you make the compiler flag the mutation, and which type annotation would you change?
Show answer
Change the declaration to const origin: readonly [number, number] = [0, 0];. A readonly tuple is not assignable to the mutable number[] parameter, so the call to scale becomes a compile error. That error forces the team to decide whether scale should return a new value instead. If scale only needs to read, change its parameter to readonly number[], and then v.push(1) inside it is an error too.