Sub topic 8
Readonly arrays and tuples
This chapter covers how readonly applies to arrays and tuples. It assumes you know basic TypeScript syntax, interfaces and type aliases, union types including undefined, and how JavaScript arrays behave. It builds on the earlier chapters showing that a readonly property is shallow and exists only at compile time.
Why a readonly property is not enough
A readonly property stops you from reassigning the property. It does not stop you from changing the array the property points to.
interface Config {
readonly tags: string[];
}
const c: Config = { tags: ["a"] };
c.tags.push("b"); // allowed: readonly only protects the tags property itself
// c.tags = []; // Error: tags is read-onlyThe push call works because it mutates the array in place and never reassigns tags. To block it, the array type itself must be read-only. TypeScript provides that through readonly array types.
Three ways to write a readonly array type
A readonly array type removes every method that mutates the array. You can write it in three equivalent forms:
const a: readonly number[] = [1, 2, 3];
const b: ReadonlyArray<number> = [1, 2, 3];
const c: Readonly<number[]> = [1, 2, 3];readonly number[]is the shorthand form. It is the one most codebases use.ReadonlyArray<number>is the generic form. It is the oldest of the three.Readonly<number[]>applies theReadonlyutility type to an array type. Since TypeScript 3.4, a homomorphic mapped type applied to an array produces a readonly array.
The readonly modifier works only as a prefix on an array type or tuple type. You cannot write readonly Array<number>. The compiler rejects that form, so use ReadonlyArray<number> instead.
What you lose, and what you keep
A readonly number[] has no push, pop, shift, unshift, splice, sort, reverse, fill or copyWithin. It also rejects index assignment and changes to length.
const xs: readonly number[] = [3, 1, 2];
// xs.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.
// xs[0] = 9; // Error: Index signature in type 'readonly number[]' only permits reading.
// xs.length = 0; // Error: Cannot assign to 'length' because it is a read-only property.
// xs.sort(); // Error: Property 'sort' does not exist on type 'readonly number[]'.Every method that returns a new value still works. These include map, filter, slice, concat, reduce, find, includes, indexOf, join, forEach, flat and flatMap. Iteration with for...of and spreading also work.
Producing changed copies
Because mutation is blocked, you build a new array when you want a different one. The usual tools are spread, slice, concat, map and filter.
const xs: readonly number[] = [3, 1, 2];
const withFour = [...xs, 4]; // number[]
const sorted = [...xs].sort((a, b) => a - b); // copy first, then sort the copy
const withoutFirst = xs.slice(1); // number[]
const doubled = xs.map((n) => n * 2); // number[]
console.log(withFour, sorted, withoutFirst, doubled, xs);Each result is an ordinary mutable number[]. The original xs is unchanged. Copying before sort matters, because sort mutates the array it is called on. In older TypeScript library typings, toSorted, toReversed, toSpliced and with may not be available. They appear when your lib setting includes ES2023 or later.
const xs: readonly number[] = [3, 1, 2];
const sorted = xs.toSorted((a, b) => a - b); // needs lib: es2023 or later
console.log(sorted);Readonly parameters
The most useful place for readonly arrays is in function parameters. A readonly number[] parameter is a promise that the function will not modify the array.
function sum(xs: readonly number[]): number {
// xs.push(1); // Error: Property 'push' does not exist on type 'readonly number[]'.
return xs.reduce((total, n) => total + n, 0);
}
const nums: number[] = [1, 2, 3];
sum(nums); // a mutable array can be passed where a readonly array is expectedCallers can pass either a mutable or a readonly array, so the signature is the most general one. A parameter typed number[] would reject readonly arrays and would give callers no assurance that their data is left alone.
Assignability runs in one direction
A mutable array is assignable to a readonly array type. The reverse is an error, because a readonly array lacks the mutating methods that number[] promises.
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[]'.This differs from readonly on object properties. A readonly property does not affect assignability, as an earlier chapter showed. Readonly arrays are different because they are a separate type with fewer methods. So the compiler does enforce this direction.
The same rule affects functions that you want to call with readonly data:
function legacy(xs: number[]): void {
xs.push(0);
}
const data: readonly number[] = [1, 2];
// legacy(data); // Error: readonly number[] is not assignable to number[]When you add readonly to a type in a codebase, the change spreads outward. Every function that receives the value and does not mutate it must also accept readonly arrays. This is why it is best to put readonly on parameters first.
The aliasing gap
The aliasing gap from the earlier chapter still applies. A readonly number[] is a view of the data, and the original mutable reference can still change it.
const mutable: number[] = [1, 2, 3];
const view: readonly number[] = mutable;
mutable.push(4);
console.log(view.length); // 4The compiler guarantees only that you cannot mutate through view. It does not guarantee that nobody else holds a mutable reference.
Readonly is compile-time only
The type readonly number[] is erased when TypeScript compiles to JavaScript. At runtime it is a normal array. Casting, any and JavaScript callers can all mutate it.
const xs: readonly number[] = [1, 2, 3];
(xs as number[]).push(4);
console.log(xs); // [1, 2, 3, 4]If you need runtime protection, use Object.freeze. Its typings return a readonly type, so the two work together.
const frozen = Object.freeze([1, 2, 3]); // readonly number[]
try {
(frozen as number[]).push(4);
} catch (e) {
console.log("runtime error:", (e as Error).message);
}Object.freeze is itself shallow, and it throws only in strict mode, which modules and classes use by default. Elsewhere, it fails silently.
Readonly tuples
A tuple is an array with a fixed length and a known type at each position. readonly applies to tuples in the same way.
type Pair = readonly [string, number];
const entry: Pair = ["age", 30];
// entry[1] = 31; // Error: Cannot assign to '1' because it is a read-only property.
// entry.push(1); // Error: Property 'push' does not exist on type 'Pair'.
const [key, value] = entry; // destructuring still works
console.log(key, value);A mutable tuple is assignable to a readonly tuple with the same element types. The reverse direction is an error, as with arrays.
A readonly tuple is also assignable to a readonly array of the union of its element types, so readonly [string, number] can be passed where readonly (string | number)[] is expected.
Tuples can carry optional elements, using ?, and readonly applies on top of that:
type Range = readonly [start: number, end?: number];
const open: Range = [0];
const closed: Range = [0, 10];
function length(r: Range): number {
const [start, end] = r;
return (end ?? Infinity) - start;
}
console.log(length(open), length(closed));Reading end gives number | undefined, which is the same result you get from an optional property. The narrowing tools from earlier in the tutorial apply here too.
Readonly arrays in generic code
Generic functions that accept arrays should usually accept readonly ones. Write the constraint as readonly T[].
function first<T>(xs: readonly T[]): T | undefined {
return xs[0];
}
console.log(first([1, 2, 3]));
console.log(first(["a"] as const));If you write xs: T[], a readonly array argument is rejected. Writing readonly T[] costs nothing and accepts both kinds.
One gotcha concerns type guards. Array.isArray narrows to any[], and that narrowing can drop readonly. When you narrow a value of type string | readonly string[], the array branch may be typed as any[] or may fail to narrow the way you expect. Check the narrowed type before relying on it, and prefer a custom type guard if the result is wrong.
function isReadonlyArray<T>(x: T | readonly T[]): x is readonly T[] {
return Array.isArray(x);
}
function toList(x: string | readonly string[]): readonly string[] {
return isReadonlyArray(x) ? x : [x];
}
console.log(toList("a"), toList(["a", "b"]));Choosing where to put readonly
The table shows common positions and what each one protects.
| Declaration | Reassign the property | Mutate the array |
|---|---|---|
| `tags: string[]` | allowed | allowed |
| `readonly tags: string[]` | blocked | allowed |
| `tags: readonly string[]` | allowed | blocked |
| `readonly tags: readonly string[]` | blocked | blocked |
Use the last form when a value should never change after it is created. Use tags: readonly string[] on a mutable object when you want to replace the whole array but never edit it in place. This is a common style for state that is updated by producing new arrays.
Common errors
Property 'push' does not exist on type 'readonly string[]'. The type is correct and the call is the mistake. Build a new array with spread orconcat.The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'. Change the receiving parameter toreadonly string[]if the function does not mutate. If it does mutate, pass a copy with[...xs].- A
readonlytype that does not seem to prevent a change. Look for an alias, a cast to a mutable type, or ananyin the path.
Exercises
Exercise
Given function f(xs: number[]): number { return xs.length; } and const data: readonly number[] = [1, 2];, why does f(data) fail to compile, and what is the best fix?
Show answer
A readonly number[] is not assignable to number[], because the readonly type lacks the mutating methods that number[] promises. Since f only reads length, change its parameter to xs: readonly number[]. That accepts both mutable and readonly arrays. Casting data as number[] would compile but removes the safety check.
Exercise
For interface Box { readonly items: string[] }, which of b.items.push("x") and b.items = [] compile, where b is a Box? Which declaration blocks both?
Show answer
b.items.push("x") compiles, because readonly only protects the property from reassignment. b.items = [] is an error. Declaring readonly items: readonly string[] blocks both.
Exercise
What is the type of sorted in const sorted = [...xs].sort() when xs is readonly number[], and why copy first?
Show answer
It is number[]. Spreading creates a new mutable array. sort mutates the array it is called on, and a readonly array has no sort method, so you sort the copy and leave xs unchanged.