Sub topic 5
Readonly arrays
This chapter assumes you know basic TypeScript annotations, union types, and the JavaScript array methods. You should also know how to write T[] and Array<T>. Here you will learn how readonly array types work, what they stop, and what they don't.
What a readonly array is
A readonly array type describes an array you can read from but not change through that reference. You can write it in two equivalent ways:
const a: readonly number[] = [1, 2, 3];
const b: ReadonlyArray<number> = [1, 2, 3];readonly T[] is the usual form. ReadonlyArray<T> is the same type written as a generic. The readonly modifier only works in front of an array or tuple type. readonly Array<number> is an error, so use ReadonlyArray<number> when you prefer the generic style.
TypeScript removes every member that mutates the array from a readonly array type. It also blocks assignment to an index and to length.
const xs: readonly number[] = [1, 2, 3];
// xs.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.
// xs.sort(); // Error: Property 'sort' does not exist on type 'readonly number[]'.
// xs[0] = 10; // 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.
const doubled = xs.map((n) => n * 2); // number[]
const firstTwo = xs.slice(0, 2); // number[]
const joined = xs.concat([4, 5]); // number[]Methods that return a new array stay available. These include map, filter, slice, concat, flatMap, and reduce. The read-only helpers indexOf, includes, find, some, every, and join also stay. The results of the array-returning methods are ordinary mutable arrays.
The mutating methods that disappear are push, pop, shift, unshift, splice, sort, reverse, fill, and copyWithin.
Why use them
A function that takes number[] makes no promise about the array. Its caller has to read the body, or trust the author, to know whether the array survives the call. A parameter typed readonly number[] is a checked promise that the function won't mutate it.
function sum(nums: readonly number[]): number {
return nums.reduce((total, n) => total + n, 0);
}
function sortedCopy(nums: readonly number[]): number[] {
// return nums.sort((a, b) => a - b); // Error: 'sort' does not exist on a readonly array
return [...nums].sort((a, b) => a - b);
}The second function shows the usual fix. If you need to sort, copy first with [...nums] or nums.slice(), then sort the copy.
Newer runtimes and a recent lib setting also provide toSorted, toReversed, toSpliced, and with. They return new arrays, so they exist on readonly arrays too. They need lib set to ES2023 or later, so check your tsconfig.json before relying on them.
const ranked = [3, 1, 2] as readonly number[];
const ascending = ranked.toSorted((a, b) => a - b); // number[]Assignability runs one way
A mutable array can be used wherever a readonly array is expected. The reverse is an error, because a readonly array might be passed to code that mutates it.
function total(nums: readonly number[]): number {
return nums.reduce((t, n) => t + n, 0);
}
function shuffle(nums: number[]): void {
nums.reverse();
}
const mutable: number[] = [1, 2, 3];
const frozen: readonly number[] = [4, 5, 6];
total(mutable); // OK
total(frozen); // OK
shuffle(mutable); // OK
// shuffle(frozen); // Error: The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.This has a practical consequence for API design. If you write function f(xs: number[]) and never mutate xs, callers holding a readonly number[] can't call you. Annotating parameters as readonly when you don't mutate them makes your function usable with both kinds of array.
Readonly is a view, not a lock
The readonly modifier exists only in the type system. It adds no runtime check and doesn't freeze anything. Anyone holding a mutable reference to the same array can still change it, and the readonly reference sees the change.
const mutable: number[] = [1, 2, 3];
const view: readonly number[] = mutable;
mutable.push(4);
console.log(view.length); // 4TypeScript allows the assignment on the second line because number[] is assignable to readonly number[]. The view reference can't mutate the array, but nothing stops the original reference from doing so.
You can also remove readonly with a type assertion, which TypeScript allows because the two types are related:
const xs: readonly number[] = [1, 2, 3];
const unsafe = xs as number[];
unsafe.push(4); // compiles, and mutates the same arrayTreat that assertion as a hole you opened on purpose. Prefer copying with [...xs] when you need a mutable version.
If you also want a runtime guarantee, Object.freeze helps. Its type signature returns a readonly array, so the compiler and the runtime agree:
const frozen = Object.freeze([1, 2, 3]); // readonly number[]
// frozen.push(4); // compile error, and a TypeError at runtime if the check were bypassedObject.freeze is shallow, like readonly, and has a small runtime cost. Use it where a bug could silently corrupt shared data, such as module-level constants.
`const` does not mean readonly
A frequent confusion is that const makes the array readonly. It doesn't. const stops you from reassigning the variable, but the array contents stay mutable, and the inferred type is a plain array.
const list = [1, 2, 3]; // number[]
list.push(4); // fine
// list = [5]; // Error: Cannot assign to 'list' because it is a constant.To get a readonly type you must either annotate it, as in const list: readonly number[] = [1, 2, 3], or use as const. The as const form is covered in a later chapter on readonly tuples. It produces a readonly tuple, which is stricter than a readonly array because it also fixes the length and the element types.
Readonly is shallow
readonly applies to the array itself, not to the elements. If the elements are objects, you can still change their properties.
type Todo = { title: string; done: boolean };
function completeFirst(todos: readonly Todo[]): void {
// todos.push({ title: "new", done: false }); // Error
todos[0].done = true; // allowed: the array is readonly, the Todo is not
}To protect the elements, make them readonly too. You can mark properties with readonly, or use the built-in Readonly<T> utility on the element type:
type ReadonlyTodo = Readonly<Todo>;
function inspect(todos: readonly ReadonlyTodo[]): number {
// todos[0].done = true; // Error: Cannot assign to 'done' because it is a read-only property.
return todos.filter((t) => t.done).length;
}Nested arrays follow the same rule. readonly number[][] is a readonly array of mutable arrays. If you want every level readonly, write readonly (readonly number[])[]. The parentheses are required, because readonly binds to the array type that immediately follows it.
Readonly in function signatures
Readonly types also work in return positions, generics, and aliases. A function that returns shared internal state can declare its result readonly so callers can't corrupt it by accident:
class Playlist {
private tracks: string[] = [];
add(title: string): void {
this.tracks.push(title);
}
list(): readonly string[] {
return this.tracks;
}
}
const p = new Playlist();
p.add("Intro");
const titles = p.list();
// titles.push("Hack"); // Error: Property 'push' does not exist on type 'readonly string[]'.This costs nothing at runtime, since list returns the same array and makes no copy. The trade-off is that the guarantee is only compile-time. If the caller needs a snapshot that won't change when the playlist changes, return a copy with [...this.tracks] instead.
For generic helpers, accept readonly T[] as well. The element type is still inferred as before:
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const n = first([10, 20, 30]); // number | undefined
const s = first(["a", "b"] as const); // "a" | "b" | undefinedThe second call works because a readonly tuple, which as const produces, is assignable to readonly T[]. A plain T[] parameter would reject it.
Summary of rules
| Operation | `number[]` | `readonly number[]` |
|---|---|---|
| Read by index | Yes | Yes |
| `map`, `filter`, `slice`, `concat` | Yes | Yes |
| `push`, `pop`, `splice`, `sort`, `reverse` | Yes | No |
| Assign `xs[i] = v` | Yes | No |
| Assign to a `number[]` variable | Yes | No, unless asserted |
| Assign to a `readonly number[]` variable | Yes | Yes |
Exercise
A function is declared as function logAll(items: string[]): void and its body only reads items. A caller has const names: readonly string[] = ["Ada", "Linus"] and calls logAll(names). What happens, and what is the best fix?
Show answer
The call is a compile-time error, because a readonly string[] is not assignable to a mutable string[]. The best fix is to change the parameter type to readonly string[]. That is accurate, since the function never mutates the array, and it lets callers pass both mutable and readonly arrays.
Exercise
Given type Todo = { title: string; done: boolean } and function reset(todos: readonly Todo[]): void { todos[0].done = false; }, does this compile? Why, and how would you make the function reject the assignment?
Show answer
It compiles. readonly Todo[] makes only the array readonly, so you can't push or reassign indexes, but the Todo objects stay mutable. To reject the assignment, make the elements readonly as well, for example readonly Readonly<Todo>[], or declare the Todo properties with readonly.