Sub topic 8
Readonly Arrays and Tuples
This chapter assumes basic TypeScript syntax, type annotations, interfaces, union types, and JavaScript arrays. It focuses on how to prevent code from changing an array or tuple through a particular variable.
Readonly arrays
A readonly array is an array whose elements cannot be changed through the variable that has the readonly type. You can write it with either of these equivalent forms:
| Syntax | Meaning |
|---|---|
| `readonly string[]` | A readonly array of strings |
| `ReadonlyArray<string>` | The same readonly array type |
Readonly arrays still support read operations such as indexing, iteration, map, filter, and reduce. They do not expose mutating methods such as push, pop, splice, or sort.
function total(values: readonly number[]): number {
// values.push(10); // Error: Property 'push' does not exist
// values[0] = 99; // Error: Index signature is read-only
return values.reduce((sum, value) => sum + value, 0);
}
const scores: number[] = [10, 20, 30];
console.log(total(scores)); // 60
console.log(scores); // [10, 20, 30]The function accepts a mutable number[] because a mutable array can safely be used where a readonly array is expected. The function promises not to modify its input, so callers do not need to copy their arrays before calling it.
Readonly tuples
A tuple is an array with a known number of elements and a known type at each position. For example, [string, number] means exactly two elements: a string followed by a number.
Add readonly before the tuple type to prevent assignments and mutating methods:
type UserEntry = readonly [id: number, name: string];
const entry: UserEntry = [42, "Ada"];
console.log(entry[0]); // 42
console.log(entry[1]); // Ada
// entry[0] = 43; // Error: Cannot assign to '0'
// entry.push("extra"); // Error: Property 'push' does not existReadonly tuples preserve the tuple's length and position types. The compiler still knows that entry[0] is a number and entry[1] is a string. A readonly tuple can also be viewed as a readonly array containing the union of its element types.
const point: readonly [number, number] = [3, 4];
function printValues(values: readonly number[]): void {
console.log(values.join(", "));
}
printValues(point); // 3, 4The reverse assignment is usually invalid. A mutable tuple might be changed by a function, so TypeScript does not allow a readonly tuple to be passed where a mutable tuple is required.
Const assertions
A const assertion, written as as const, creates readonly arrays and readonly object properties. It also preserves literal values instead of widening them to general types.
const directions = ["up", "down", "left", "right"] as const;
type Direction = (typeof directions)[number];
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up"); // valid
// move("sideways"); // Error
// directions.push("center"); // Error: directions is readonlyHere, directions has the type readonly ["up", "down", "left", "right"]. The Direction type is the union "up" | "down" | "left" | "right".
Choosing the right type
Use readonly T[] for a sequence when the length and position types do not matter. Use a readonly tuple when each position has a specific meaning.
A readonly parameter is often the best default for functions that only inspect their input. It documents the function's behavior and accepts both mutable arrays and readonly arrays.
If you need to change a readonly array, create a new mutable array with a spread:
const original: readonly number[] = [1, 2, 3];
const updated: number[] = [...original, 4];
console.log(updated); // [1, 2, 3, 4]Exercise
What is the most suitable type for a function parameter that reads any number of numbers but must not modify them?
Show answer
readonly number[]. It accepts both mutable and readonly number arrays while preventing mutation inside the function.