Arrays and tuples
Overview
Arrays hold lists; tuples hold small fixed-size records. Both are ordinary JavaScript arrays at run time — the difference is entirely in what TypeScript lets you do with them.
Arrays
Two equivalent spellings:
const scores: number[] = [91, 78, 85];
const names: Array<string> = ["Asha", "Ben"];T[] is the common style; Array<T> is the same thing written as a generic (Generic types).
Usually you don’t annotate at all — TypeScript infers from the contents:
const scores = [91, 78, 85]; // number[]
const mixed = [1, "two", 3]; // (string | number)[]
scores.push("100");
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.Annotate empty arrays, which have nothing to infer from:
const results: string[] = [];Array methods stay typed
Every array method knows the element type and passes it on:
const names = ["asha", "ben", "chen"];
const upper = names.map((n) => n.toUpperCase()); // string[]
const long = names.filter((n) => n.length > 3); // string[]
const lengths = names.map((n) => n.length); // number[]
const found = names.find((n) => n.startsWith("b")); // string | undefinedNote find: it might not find anything, so TypeScript includes undefined in the result. Before you can call found.toUpperCase(), you must check it (null and undefined).
Indexing and noUncheckedIndexedAccess
What’s the type of names[10]? In plain strict mode TypeScript says string — and trusts you that index 10 exists. That’s how a lot of “undefined is not an object” bugs slip through.
The noUncheckedIndexedAccess option (on in this course’s tsconfig) makes TypeScript honest:
const first = names[0]; // string | undefined
first.toUpperCase();
// error TS18048: 'first' is possibly 'undefined'.
if (first !== undefined) {
first.toUpperCase(); // ✓ checked
}
names[0] ?? "nobody"; // or provide a fallbackfor…of loops and array methods don’t have this problem — they only visit items that exist — so prefer them over index loops.
readonly arrays
Mark arrays you shouldn’t change as readonly:
function average(values: readonly number[]): number {
values.push(0);
// error TS2339: Property 'push' does not exist on type 'readonly number[]'.
return values.reduce((sum, v) => sum + v, 0) / values.length;
}readonly number[] (also written ReadonlyArray<number>) simply has no mutating methods — no push, pop, splice, sort or reverse. Non-mutating ones (map, filter, slice, toSorted) work fine. It’s a great type for function parameters: it promises callers that you won’t modify their data. To sort, copy first: [...values].sort() or values.toSorted().
readonly is a compile-time check only. The array can still be changed at run time by code that ignores the types; use Object.freeze if you need that.
Tuples
A tuple is an array with a fixed number of items, where each position has its own type:
const entry: [string, number] = ["Asha", 91];
const [name, score] = entry; // name: string, score: number
entry[2];
// error TS2493: Tuple type '[string, number]' of length '2' has no element at index '2'.Common uses:
- returning several values from a function —
useStatein React returns a tuple[value, setValue]; - pairs and coordinates:
[x: number, y: number]; Object.entries(obj), which returns[string, T][].
Labelled and optional elements
Labels document what each position means (and show in the editor), without changing the type:
type Entry = [name: string, score: number];
type Range = [start: number, end?: number]; // optional last element
type Path = [first: string, ...rest: string[]]; // at least one stringTuples need annotations
Without a type, TypeScript infers an array, not a tuple:
const point = [3, 4]; // number[] — any length
const point2: [number, number] = [3, 4]; // tuple
const point3 = [3, 4] as const; // readonly [3, 4]as const is covered in as const and satisfies.
When to use an object instead
Tuples are compact but positional: what was row[3] again? Once a record has more than two or three fields, or you pass it around widely, an object with named properties is clearer: { name: "Asha", score: 91 }.
Remember: arrays for lists, tuples for small fixed records,
readonlyfor data you promise not to change — and withnoUncheckedIndexedAccess, always deal with the item that might not be there.
Leaderboard
Write three fully typed functions. (1) topScores(scores: readonly number[], n: number): number[] returns the n highest scores, highest first, without changing the input. (2) toEntries(names: string[], scores: number[]): [name: string, score: number][] pairs them up. (3) leader(entries: readonly [string, number][]): string returns "<name> (<score>)" for the highest score, or "nobody" for an empty list — handle the possibly-undefined first element without !. Print the top 3, the entries, and the leader; then show (with // @ts-expect-error) that topScores cannot sort a readonly array in place.
const names = ["Asha", "Ben", "Chen", "Dee"];
const scores = [78, 91, 85, 62];
// 1. topScores
// 2. toEntries
// 3. leaderconst names = ["Asha", "Ben", "Chen", "Dee"];
const scores = [78, 91, 85, 62];
// 1. topScores
function topScores(scores: readonly number[], n: number): number[] {
return [...scores].sort((a, b) => b - a).slice(0, n);
}
// 2. toEntries
function toEntries(names: string[], scores: number[]): [name: string, score: number][] {
return names.map((name, i) => [name, scores[i] ?? 0]);
}
// 3. leader
function leader(entries: readonly [string, number][]): string {
const sorted = [...entries].sort((a, b) => b[1] - a[1]);
const first = sorted[0]; // [string, number] | undefined
if (first === undefined) return "nobody";
const [name, score] = first;
return `${name} (${score})`;
}
console.log(topScores(scores, 3)); // [ 91, 85, 78 ]
console.log(scores); // unchanged: [ 78, 91, 85, 62 ]
const entries = toEntries(names, scores);
console.log(entries);
console.log(leader(entries)); // Ben (91)
console.log(leader([])); // nobody
function sortInPlace(values: readonly number[]) {
// @ts-expect-error -- readonly arrays have no sort() method
values.sort();
}Summary
number[](orArray<number>) is a list of any length where every item is a number.- Tuples like
[string, number]have a fixed length and a type for each position; label positions for readability. readonly number[]removes mutating methods such aspushandsort— use it for parameters you shouldn’t change.- With
noUncheckedIndexedAccess,items[i]has typeT | undefined, so you must handle missing items. - Array methods keep their types:
map,filterandfindall return precisely typed results.