Sub topic 13
Arrays, tuples, and readonly arrays
This chapter assumes you know basic TypeScript syntax, how structural assignability works for objects, and the idea of covariance and contravariance from the previous chapters. It covers how T[], tuples, and readonly arrays relate to each other as source and target types.
Arrays are covariant in their element type
Dog[] is assignable to Animal[] whenever Dog is assignable to Animal. This is covariance: the relation between the element types carries over to the array types.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
const dogs: Dog[] = [{ name: "Rex", bark() {} }];
const animals: Animal[] = dogs; // OK: Dog is assignable to AnimalReading is safe here. Every element of animals really is an Animal. Writing is not safe, because animals and dogs are the same array:
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
const dogs: Dog[] = [];
const animals: Animal[] = dogs;
animals.push({ name: "cat" }); // compiles
dogs[0].bark(); // compiles, but fails at runtime: bark is not a functionA sound system would treat a mutable array as invariant, because it is both read from and written to. TypeScript accepts the unsound case on purpose. Treating arrays as invariant would reject a great deal of ordinary code, such as passing a Dog[] to a function that only reads Animal[].
readonly arrays remove the write hazard
readonly T[] (also written ReadonlyArray<T>) has no mutating methods such as push, pop, or sort. With only reads left, covariance is sound for it.
Assignability between the two forms runs in one direction:
T[]is assignable toreadonly T[].readonly T[]is not assignable toT[].
const mutable: number[] = [1, 2, 3];
const frozen: readonly number[] = mutable; // OK
const back: number[] = frozen;
// Error: The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.
frozen.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'The one-way rule is a deliberate exception to structural typing. Structurally, number[] has every member of readonly number[], so readonly number[] lacks extra members and might be expected to be a valid source for number[]. The compiler rejects it explicitly, because accepting it would let you call push through the mutable alias.
The practical rule: declare function parameters as readonly T[] when the function does not mutate them. Callers can then pass either kind of array.
function sum(values: readonly number[]): number {
return values.reduce((total, v) => total + v, 0);
}
const live: number[] = [1, 2];
const fixed: readonly number[] = [3, 4];
console.log(sum(live), sum(fixed)); // 3 7Note that readonly is a compile-time check only. It does not freeze the array at runtime, and the mutable alias above can still change the contents that frozen sees.
Tuples
A tuple is an array type with a fixed length and a known type at each position. Its assignability rules differ from those of plain arrays.
const pair: [string, number] = ["a", 1];
const arr: (string | number)[] = pair; // OK: a tuple is assignable to an array of the union of its elements
const bad: [string, number] = ["a", 1, true];
// Error: Source has 3 element(s) but target allows only 2.The rules to remember:
- A tuple is assignable to an array type whose element type accepts every position.
[string, number]is assignable to(string | number)[]. - An array is not assignable to a tuple, because its length is unknown.
string[]is not assignable to[string]. - Tuples of different lengths are not assignable to each other, because the
lengthproperty is a literal type (2,3, and so on). - Each position is compared separately, covariantly.
const list: string[] = ["a", "b"];
const one: [string] = list;
// Error: Target requires 1 element(s) but source may have fewer.Optional elements and rest elements loosen the length rule. A tuple with an optional element has a length that is a union of literals.
type Range = [start: number, end?: number];
const r1: Range = [1]; // OK
const r2: Range = [1, 5]; // OK
const r3: Range = [1, 5, 9]; // Error: Source has 3 element(s) but target allows only 2.
type Row = [label: string, ...values: number[]];
const row: Row = ["total", 1, 2, 3]; // OKTuples and readonly
The same one-way rule applies. [string, number] is assignable to readonly [string, number], but not the reverse.
A common trap is that array literals are inferred as arrays, not tuples, unless context says otherwise. Use an annotation or as const.
function move(point: readonly [number, number]): void {}
const p = [1, 2];
move(p);
// Error: Argument of type 'number[]' is not assignable to parameter of type 'readonly [number, number]'.
const q = [1, 2] as const; // type: readonly [1, 2]
move(q); // OKas const produces a readonly tuple of literal types. That makes it assignable to readonly [number, number], but not to the mutable [number, number].
Each arrow means "is assignable to". No arrow runs back up the diagram.
Edge cases
- Empty array literals.
const xs = []has an evolving type that starts asnever[]under strict settings and widens as you push. Annotate it when it escapes the local scope. - Union of arrays versus array of union.
string[] | number[]is not the same as(string | number)[].string[]is assignable to both, but a value of the first type cannot receive anumberthroughpushwithout narrowing. any[]. Any array is assignable toany[], andany[]is assignable to any array type. This silently disables element checks.- Spread and
Array.from. Spreading a tuple into an array literal keeps tuple positions only when the contextual type is a tuple.
Exercise
Which of these assignments is an error, and why? (1) const a: readonly string[] = ["x"]; (2) const b: string[] = a; (3) const c: [string, string] = ["x", "y"] as const;
Show answer
(1) is fine, since an array literal is assignable to a readonly array. (2) is an error, because a readonly array is not assignable to a mutable array: it would allow mutation through b. (3) is also an error, because as const produces readonly ["x", "y"], and a readonly tuple is not assignable to the mutable tuple [string, string].
Exercise
Why is string[] not assignable to [string, string], even though ["a", "b"] is?
Show answer
The type string[] has no fixed length, so the compiler cannot guarantee two elements. The literal ["a", "b"] is checked against the tuple annotation directly, where the contextual type makes it a two-element tuple.