Basic · 4 of 13 · 12 min read
Arrays and tuples
Two spellings of the array type, what a tuple adds, and the two holes — index access and push — where the compiler stops protecting you.
- Arrays
- Tuples
An array type says what the elements are. A tuple type says how many there are and what each position holds. Both compile to the same JavaScript array, so everything here is a promise the compiler keeps — or, in two specific places, does not.
< class=“callout” data-kind=“takeaway”>
items[0] is typed as the element type even when the array is empty. The compiler does not track
length, which is why noUncheckedIndexedAccess exists and why it is not in strict.
Two spellings, one type
const a: string[] = ["x"];
const b: Array<string> = a; // identical — the bracket form is shorthand
const nested: number[][] = [[1], [2]];
const alsoNested: Array<Array<number>> = nested;
console.log(a.length, nested[0]?.[0]); // 1 1
Use the bracket form by default. The generic spelling is occasionally clearer with a long element type, and it is what you will see in declaration files.
The index hole
const items: string[] = [];
const first = items[0]; // typed string
console.log(first.toUpperCase()); // compiles — throws at runtime
The compiler knows the element type and nothing about the length, so an out-of-range read is typed
as if it succeeded. noUncheckedIndexedAccess fixes it by adding undefined to every index read:
// with "noUncheckedIndexedAccess": true
const items: string[] = [];
const first = items[0]; // string | undefined
// console.log(first.toUpperCase()); // 'first' is possibly 'undefined'
console.log(first?.toUpperCase() ?? "empty");
// at() returns the union regardless of the flag:
console.log(items.at(0)?.toUpperCase() ?? "empty");
It is not in strict because it is noisy in loops where you know the index is valid. Turning it
on is still usually right; the noise is where real bugs live.
// The noise, and the fix that keeps the check honest:
const names = ["Ana", "Beto"];
for (const name of names) console.log(name.toUpperCase()); // no index, no undefined
console.log(names.map((n) => n.toUpperCase())); // same
Readonly arrays
function total(values: readonly number[]): number {
// values.push(1); // Property 'push' does not exist on 'readonly number[]'
return values.reduce((sum, n) => sum + n, 0);
}
const mutable = [1, 2, 3];
console.log(total(mutable)); // 6 — a mutable array goes in fine
const locked: readonly number[] = [1, 2];
// const back: number[] = locked; // not assignable — the other direction fails
console.log(locked.concat(3)); // [1,2,3] — non-mutating methods remain
readonly T[] and ReadonlyArray<T> are the same type. It is compile-time only — nothing is
frozen — and the right default for a parameter the function only reads.
Tuples
A tuple fixes the length and gives each position its own type:
type Entry = [string, number];
const pair: Entry = ["age", 33];
const [key, value] = pair; // key: string, value: number
// const wrong: Entry = [33, "age"]; // types in the wrong slots
// const tooMany: Entry = ["a", 1, true]; // length is part of the type
console.log(key, value); // "age" 33
Named members document what the positions mean, and change nothing else:
type Range = [start: number, end: number];
const r: Range = [0, 10];
console.log(r[0], r[1]); // 0 10
Optional and rest elements make the length a range:
type Args = [name: string, age?: number, ...tags: string[]];
const a: Args = ["Ana"];
const b: Args = ["Ana", 30];
const c: Args = ["Ana", 30, "admin", "staff"];
console.log(a.length, c.length); // 1 4
console.log(b[1]?.toFixed(0) ?? "no age"); // "30"
string[] |
[string, number] |
|
|---|---|---|
| Length | any | fixed (or a range, with ? / rest) |
| Type per position | the same for all | one each |
| Destructuring | every binding is the element type | each binding is its own type |
| Natural use | a list of things | a pair, a return of two values |
The push hole
Tuple length is enforced for literals and index writes, and not for the mutating methods:
const pair: [string, number] = ["a", 1];
pair[0] = "b"; // fine
// pair[2] = 4; // Tuple type has no element at index '2'
pair.push(3); // allowed! push is typed against string | number
console.log(pair.length); // 3 — the tuple type says 2
A known soundness gap. readonly closes it:
const locked: readonly [string, number] = ["a", 1];
// locked[0] = "b"; // Cannot assign to '0' — it is read-only
// locked.push("c"); // push does not exist on a readonly tuple
console.log(locked.length); // 2, and it stays 2
Parentheses matter
const mixed: (string | number)[] = ["x", 1]; // each element may be either
const either: string[] | number[] = ["x", "y"]; // all strings, or all numbers
// const bad: string[] | number[] = ["x", 1]; // matches neither
for (const value of mixed) {
if (typeof value === "string") console.log(value.toUpperCase());
else console.log(value.toFixed(1));
}
The second form also loses methods, because push on a union of two array types has no single
signature the compiler can call.
Getting a tuple out of a literal
A plain literal is inferred as an array, so a tuple needs an annotation, as const, or a generic
that preserves it:
const loose = [1, "two"]; // (string | number)[]
const tuple: [number, string] = [1, "two"];
const frozen = [1, "two"] as const; // readonly [1, "two"]
function pair<T, U>(a: T, b: U): [T, U] {
return [a, b];
}
const inferred = pair(1, "two"); // [number, string]
console.log(loose.length, tuple[1], frozen[0], inferred[1]);
The as const form is the one to remember — it is how const roles = [...] as const becomes a
union with (typeof roles)[number].
Common mistakes
Trusting an index read
Mistake. const first = items[0]; first.toUpperCase();
Why it fails. The type is the element type whatever the length, so an empty array compiles and
throws.
What to do instead. Turn on noUncheckedIndexedAccess, or use at(), find, or a for...of
that never indexes.
Leaving an empty array literal unannotated
Mistake. const items = []; followed by pushes.
Why it fails. It becomes an evolving any[], so nothing about the elements is ever checked.
What to do instead. const items: string[] = [].
Expecting a tuple to stop push
Mistake. Treating [string, number] as a fixed-size structure at runtime.
Why it fails. The mutating methods are typed against the union of the element types, so push
compiles and the length drifts.
What to do instead. readonly [string, number] when the length is part of the contract.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
What is the difference between string[] and Array<string>?
An array type promises what the elements are, not how many there are.
This compiles, but crashes at runtime. Why does the compiler allow it?
const items: string[] = [];
const first = items[0];
console.log(first.toUpperCase());What does a tuple type add over an array type?
Tuple element types are positional, and push is the hole in that promise.
Which of these lines is rejected by the compiler?
const pair: [string, number] = ["a", 1];
pair[0] = "b";
pair[1] = 2;
pair.push(3);
pair[2] = 4;Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.