Arrays and tuples
Typing lists of any length with `T[]`, and fixed-position data with tuples: named, optional, and rest elements, and why tuples need annotating.
Arrays and tuples
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- An array type describes a list of any length whose elements share one type, written `string[]` or the identical `Array<string>`.
- For an array of mixed elements, wrap the union in parentheses: `(string | number)[]` is a list of strings and numbers, while `string | number[]` is a single string or an array of numbers.
- A tuple fixes both the length and the type at each position, as in `[string, number]`, so reading index `1` gives a `number` and reading index `2` is an error.
- Tuple elements can be named (`[x: number, y: number]`), optional (`[number, number?]`), or gathered with a rest element (`[string, ...number[]]`).
- TypeScript never infers a tuple from an array literal on its own; `["ada", 36]` becomes `(string | number)[]`, so you get a tuple by annotating or by writing `as const`.
Two different jobs for square brackets
JavaScript uses one data structure, the array, for two quite different jobs. Sometimes it is a list: shopping cart items, search results, a column of numbers. The length is not known ahead of time and every element plays the same role. Other times it is a record with positions instead of names: [latitude, longitude], or the [value, setValue] pair a React hook returns. The length is fixed and each slot means something different.
At runtime both are just arrays. TypeScript gives them separate types, because the checks you want are different. For a list, you want every element to be the right kind. For a positional record, you want each slot to be the right kind and nothing extra.
Array types
A list of strings is written string[]. The generic form Array<string> means exactly the same thing; most codebases pick the short form and stick with it.
const tags: string[] = ["ts", "types"];
const scores: Array<number> = [91, 78, 85];
tags.push("arrays"); // fine
tags.push(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Usually you don’t need the annotation at all, since ["ts", "types"] is inferred as string[]. The exception is an empty array, which has nothing to infer from. Annotate it: const ids: number[] = [];.
When elements can be more than one type, put a union in parentheses:
const mixed: (string | number)[] = ["a", 1, "b", 2];
const confusing: string | number[] = "just a string"; // also valid, and a different type
Without the parentheses, the [] binds only to number, and the type means “a string, or an array of numbers”. Unions get their own lesson; here, just remember where the parentheses go.
One honest limit: reading scores[10] gives type number, even though at runtime it is undefined. TypeScript assumes indexes are in bounds unless you turn on noUncheckedIndexedAccess, covered in the strict flags lesson.
Tuples: fixed length, typed positions
A tuple type lists the type of each position:
let entry: [string, number] = ["ada", 36];
const name = entry[0]; // string
const age = entry[1]; // number
entry[2]; // Error: Tuple type '[string, number]' of length '2' has no element at index '2'.
entry = [36, "ada"]; // Error: Type 'number' is not assignable to type 'string'.
Think of a tuple as a parcel form with numbered boxes: box 1 is the name, box 2 is the age. Swapping the contents of the boxes is caught, and so is writing in a box that is not on the form.
Named elements
[number, number] does not say which number is which. Tuple elements can carry labels:
type Coordinate = [lat: number, lng: number];
function distanceFrom(origin: Coordinate) {
const [lat, lng] = origin;
return Math.hypot(lat, lng);
}
Labels change nothing about what is accepted. They show up in editor hovers and in error messages, which is enough to stop someone passing longitude first.
Optional elements
A trailing ? makes a position optional, which also makes the tuple’s length a range:
type Point = [x: number, y: number, z?: number];
const flat: Point = [1, 2];
const deep: Point = [1, 2, 3];
const third = deep[2]; // number | undefined
Optional elements can only come at the end, because a gap in the middle would make every later position ambiguous.
Rest elements
A rest element says “then any number of these”:
type LogLine = [level: string, ...details: number[]];
const short: LogLine = ["info"];
const long: LogLine = ["warn", 404, 12, 7];
const bad: LogLine = [404]; // Error: Type 'number' is not assignable to type 'string'.
The rest element can sit at the start or middle too, as in [...string[], number] for “some strings, then a number”. This is how TypeScript types a function’s argument list, which becomes useful later in the typing functions group.
Why tuples need to be asked for
This is the part that trips people up:
const pair = ["ada", 36]; // (string | number)[], not [string, number]
const pinned: [string, number] = ["ada", 36]; // [string, number]
const frozen = ["ada", 36] as const; // readonly ["ada", 36]
TypeScript never guesses that an array literal is a tuple. Most array literals are lists, and inferring a fixed length would make ordinary code like pair.push(...) fail. So you opt in: annotate with a tuple type, or write as const, which infers the narrowest possible type: a read-only tuple of literal values. The same applies to function return values; if a function returns [value, setValue], annotate the return type, or callers get a union array and lose track of which position is which.
The readonly in that last hover matters. A plain [string, number] still has push, and entry.push("oops") compiles even though the tuple now has three elements. A readonly tuple has no mutating methods at all. The readonly and immutability lesson picks this up.
About the video
Net Ninja’s tuples episode from his 2023 crash course shows the core idea well: a tuple type pins the type at each position, and the editor complains when the order or the length is wrong. That is all it covers. Array types themselves are in the same series’ episode 5, linked below, and neither video touches named, optional, or rest elements, or why tuples have to be requested explicitly; the sections above carry that part. The Rethinking UI video in the links is useful once the syntax is clear, because it focuses on where tuples earn their place in real code.
Check yourself
What is the difference between `(string | number)[]` and `string | number[]`?
The first is an array whose elements may each be a string or a number. The second is a union of two whole things: either a single `string`, or an array of numbers. The parentheses decide whether the `[]` applies to the union or only to `number`.
Why does `const entry = ["ada", 36]` not have the type `[string, number]`?
An array literal is usually a list that will grow, shrink, or be mapped, so TypeScript infers the more flexible `(string | number)[]`. It has no way to know you meant the positions to be fixed. Annotating with `[string, number]` or writing `as const` tells it so.
What do names in a tuple type such as `[lat: number, lng: number]` change?
Nothing about what is allowed; `[lat: number, lng: number]` accepts exactly what `[number, number]` accepts. The names exist for people: they show up in editor hovers and in function signatures that use the tuple, so `lat` and `lng` cannot be confused.
Can you call `push` on a value of type `[string, number]`?
Yes, and it is a known gap. The tuple type still has the array methods, so `push("x")` compiles even though the result no longer matches the declared length. Making the tuple `readonly [string, number]` removes `push` and closes the gap.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.