Arrays and tuples

Topic 3 of 4 in Everyday types7 min readIntermediateFree course

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 vs tuples. An array has any length and every item the same type: const scores: number[] = [91, 78, 85]; — each item is a number, and there can be more. A tuple has a fixed length and each position has its own type: const entry: [string, number] = [“Asha”, 91]; — position 0 is a string, position 1 a number, and entry[2] is an error. Add readonly to stop changes: readonly number[] and readonly [string, number]. Name tuple positions for readability: [name: string, score: number].

Arrays

Two equivalent spellings:

TypeScript
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:

TypeScript
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:

TypeScript
const results: string[] = [];

Array methods stay typed

Every array method knows the element type and passes it on:

TypeScript
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 | undefined

Note 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:

TypeScript
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 fallback

for…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:

TypeScript
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:

TypeScript
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 — useState in 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:

TypeScript
type Entry = [name: string, score: number];
type Range = [start: number, end?: number];       // optional last element
type Path = [first: string, ...rest: string[]];   // at least one string

Tuples need annotations

Without a type, TypeScript infers an array, not a tuple:

TypeScript
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, readonly for data you promise not to change — and with noUncheckedIndexedAccess, always deal with the item that might not be there.

Exercise

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.

TypeScript
const names = ["Asha", "Ben", "Chen", "Dee"];
const scores = [78, 91, 85, 62];

// 1. topScores

// 2. toEntries

// 3. leader

Summary

  • number[] (or Array<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 as push and sort — use it for parameters you shouldn’t change.
  • With noUncheckedIndexedAccess, items[i] has type T | undefined, so you must handle missing items.
  • Array methods keep their types: map, filter and find all return precisely typed results.