Sub topic 5
Arrays and Tuples
This chapter assumes you know basic JavaScript arrays, the primitive types from earlier chapters, and how to run tsc or use a TypeScript-aware editor. It covers how TypeScript types arrays, how tuples differ from arrays, and the errors people hit most often.
Arrays: one type, any length
An array type describes a list where every element has the same type and the length is unknown. You can write it two ways.
const scores: number[] = [90, 85, 72];
const names: Array<string> = ["Ada", "Grace"];number[] and Array<number> mean the same thing. Most codebases prefer number[] for simple element types and Array<...> when the element type is complex. Pick one style and keep it consistent.
When you initialize an array without an annotation, TypeScript infers the element type from the values.
const a = [1, 2, 3]; // number[]
const b = ["x", "y"]; // string[]
const c = [1, "two", true]; // (string | number | boolean)[]
const d = []; // any[] while empty, then evolves as you pushMixed values produce a union element type, so c is an array of string | number | boolean. Reading from it gives you the union, and you must narrow before using type-specific methods.
An empty array literal is a special case. With strict enabled, a variable declared as const d = [] gets an "evolving" type that grows as you push values. If you pass it somewhere before it has any elements, you can get an implicit any[] error. Annotate empty arrays explicitly.
const queue: string[] = [];
queue.push("job-1");
// queue.push(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.Indexing and the unchecked-access gap
By default, indexing an array returns the element type, even if the index is out of range.
const letters: string[] = ["a", "b"];
const third = letters[5]; // type is string, runtime value is undefined
console.log(third.toUpperCase()); // compiles, throws TypeError at runtimeTypeScript does not track array length for T[], so it cannot know the index is invalid. The compiler option noUncheckedIndexedAccess closes this gap. With it on, letters[5] has type string | undefined, and you must handle the missing case.
const maybe = letters[5];
if (maybe !== undefined) {
console.log(maybe.toUpperCase());
}This option is not part of strict. Turn it on explicitly if you want the extra safety. The cost is more narrowing in loops that index by number.
Readonly arrays
A readonly array type removes the methods that mutate the array.
const ids: readonly number[] = [1, 2, 3];
// ids.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.
// ids[0] = 9; // Error: Index signature in type 'readonly number[]' only permits reading.
const copy: number[] = [...ids, 4]; // fine: a new arrayReadonlyArray<number> is the long form. A mutable number[] is assignable to readonly number[], but not the other way around.
function total(values: readonly number[]): number {
return values.reduce((sum, v) => sum + v, 0);
}
const mutable: number[] = [1, 2];
total(mutable); // okDeclare parameters as readonly T[] when the function only reads the array. Callers can then pass either kind, and the function promises not to change the input. Note that readonly is a compile-time check only. At runtime the array is still an ordinary mutable array.
Tuples: fixed positions, known types
A tuple is an array type with a fixed length where each position has its own type.
const entry: [string, number] = ["age", 30];
const key = entry[0]; // string
const value = entry[1]; // number
// entry[2]; // Error: Tuple type '[string, number]' of length '2' has no element at index '2'.Tuples are useful when position carries meaning, such as a key and value pair, coordinates, or a function that returns two things.
Inference gives arrays, not tuples
TypeScript infers an array literal as an array unless context says otherwise.
const pair = ["age", 30];
// pair is (string | number)[]
const typed: [string, number] = ["age", 30];
// typed is [string, number]This causes a common error when passing a literal-built array to a function that expects a tuple.
function show(entry: [string, number]): string {
return `${entry[0]}=${entry[1]}`;
}
const pair = ["age", 30];
// show(pair);
// Error: Argument of type '(string | number)[]' is not assignable to parameter of type '[string, number]'.
show(["age", 30]); // ok: the parameter type gives context
const fixed: [string, number] = ["age", 30];
show(fixed); // okFix it by annotating the variable, or by using as const (covered in a later chapter).
Optional, rest, and labeled elements
Tuples support optional elements, rest elements, and labels that document each position.
type Range = [start: number, end?: number];
const open: Range = [10];
const closed: Range = [10, 20];
type Row = [id: number, ...tags: string[]];
const row: Row = [1, "new", "urgent"];
function bounds(r: Range): number {
const [start, end = start] = r;
return end - start;
}Labels such as start and end change nothing at runtime or in assignability. They show up in editor hints and error messages. An optional element has type T | undefined when read, and optional elements must come last (before any rest element only in specific forms, so keep them at the end for simplicity).
Destructuring and return values
Tuples work well with destructuring, because each name gets its own type.
function minMax(values: number[]): [number, number] {
return [Math.min(...values), Math.max(...values)];
}
const [lo, hi] = minMax([4, 9, 2]);
// lo: number, hi: numberWithout the return annotation, minMax would be inferred as returning number[], and lo would be number only because indexing is unchecked. Annotate tuple return types so the length is enforced.
Tuples are still arrays at runtime
A tuple compiles to a plain JavaScript array. TypeScript allows methods that change length on a mutable tuple in some cases, which can break the fixed-length promise.
const point: [number, number] = [1, 2];
point.push(3); // compiles: push accepts number
console.log(point); // [1, 2, 3] at runtimeThe compiler checks assignments and indexing, but push is declared on Array<number>, so it is permitted. Use readonly [number, number] to block this.
const safe: readonly [number, number] = [1, 2];
// safe.push(3); // Error: Property 'push' does not exist on type 'readonly [number, number]'.Choosing between arrays and tuples
| Situation | Use |
|---|---|
| List of same-kind items, length varies | `T[]` |
| Fixed small group, position has meaning | tuple |
| Function only reads the list | `readonly T[]` |
| Many fields, names matter | object type |
If a tuple grows beyond two or three elements, or you find yourself remembering what index 2 means, switch to an object type. Named properties are easier to read and safer to change.
Common errors
- Unannotated tuple literals.
const p = [1, 2]isnumber[], not[number, number]. Annotate it when you need a tuple. - Assuming indexing is safe.
arr[i]is notundefined-checked unlessnoUncheckedIndexedAccessis on. - Mutating through
push. Tuples and arrays that are notreadonlyacceptpush,pop, andsplice. - Passing a mutable-only parameter. A function that takes
number[]rejects areadonly number[]argument. Acceptreadonly number[]when you do not mutate. - Mixed array literals.
[1, "a"]gives a union element type, which forces narrowing on every read.
Exercise
What are the types of a and b below, and why does use(a) fail while use(b) compiles?
function use(p: [string, number]): void {}
const a = ["id", 7];
const b: [string, number] = ["id", 7];
use(a);
use(b);
Show answer
a is inferred as (string | number)[] because array literals infer as arrays, so it is not assignable to [string, number] and use(a) errors. b is annotated as the tuple [string, number], so use(b) compiles.
Exercise
Write a function first that takes a read-only array of strings and returns the first element, with a return type that admits the empty case. Then say why readonly string[] is a better parameter type than string[].
Show answer
function first(items: readonly string[]): string | undefined { return items[0]; } The return type includes undefined because an empty array has no first element. readonly string[] accepts both mutable and readonly arrays and tells readers the function will not modify its input, while string[] would reject readonly arguments.