Sub topic 5
Readonly arrays
Assume you know JavaScript arrays, basic TypeScript annotations, and union types. This chapter focuses on preventing a function from mutating an array through the reference it receives.
A readonly array is an array type that does not expose methods that change the array. TypeScript supports two equivalent forms:
function total(values: readonly number[]): number {
return values.reduce((sum, value) => sum + value, 0);
}
function average(values: ReadonlyArray<number>): number {
return total(values) / values.length;
}
const scores = [80, 90, 70];
console.log(total(scores));
console.log(average(scores));readonly number[] and ReadonlyArray<number> both mean “an array whose elements are numbers and whose contents cannot be changed through this reference.”
What readonly prevents
Readonly affects the type of the reference, not the array object itself. Methods such as push, pop, splice, and sort are unavailable:
function addScore(scores: readonly number[], score: number): void {
// scores.push(score);
// Error: Property 'push' does not exist on type 'readonly number[]'.
console.log(score);
}
const scores: number[] = [80, 90];
addScore(scores, 100);
scores.push(100); // Allowed through the mutable scores reference.
console.log(scores);A mutable array can be passed to a function expecting a readonly array. This is useful because the function promises not to mutate its input. The reverse assignment is not allowed:
const mutable: number[] = [1, 2, 3];
const view: readonly number[] = mutable;
// const copy: number[] = view;
// Error: A readonly array cannot be assigned to a mutable array.
view.forEach((value) => console.log(value));The original mutable reference can still change the array. The readonly view does not make the array immutable everywhere.
Readonly parameters and array methods
Use readonly array parameters when a function only reads its input. This lets callers pass either mutable or readonly arrays:
type User = {
name: string;
active: boolean;
};
function activeNames(users: readonly User[]): string[] {
return users
.filter((user) => user.active)
.map((user) => user.name);
}
const users: readonly User[] = [
{ name: "Ada", active: true },
{ name: "Linus", active: false },
];
const names = activeNames(users);
console.log(names);Methods that create a result, such as map, filter, and slice, remain available. Their results are usually ordinary mutable arrays. The input stays unchanged, but the returned array can be edited.
const values: readonly number[] = [1, 2, 3];
const doubled = values.map((value) => value * 2);
doubled.push(8);
console.log(doubled);The callback can also narrow union members. A type-guard callback tells TypeScript the element type of the filtered result:
function onlyStrings(values: readonly (string | null)[]): string[] {
return values.filter((value): value is string => value !== null);
}
console.log(onlyStrings(["a", null, "b"]));Choosing readonly arrays
| Situation | Recommended type |
|---|---|
| The function must add, remove, or reorder elements | `T[]` |
| The function only reads elements | `readonly T[]` |
| A public API should accept both mutable and readonly arrays | `readonly T[]` |
| The caller must receive a mutable new result | `T[]` as the return type |
The main design rule is simple: accept the least powerful type that your function needs. A read-only function should usually accept readonly T[], which documents its behavior and prevents accidental mutation.
Exercise
Why can a number[] be passed to a function accepting readonly number[], and why is the reverse assignment rejected?
Show answer
A mutable array supports every read operation required by a readonly array, so it is safe to pass it in. A readonly array does not guarantee that mutation is safe, so TypeScript rejects passing it where a mutable array is required.