Sub topic 6
Passing readonly values to functions
TypeScript can infer a readonly tuple from an array literal when you use as const. A readonly value cannot be changed through that type. This protects the caller from functions that might mutate their input.
This chapter assumes that you know basic TypeScript types, arrays, object types, unions, and the difference between let and const.
The assignability rule
A mutable array type, such as number[], promises that the array can be changed. A readonly array type, such as readonly number[], makes no such promise.
Because of that difference, TypeScript does not allow a readonly array to be passed to a function that expects a mutable array.
function addTotal(values: number[]): number {
values.push(0);
return values.reduce((total, value) => total + value, 0);
}
const fixedValues = [1, 2, 3] as const;
// Error:
// addTotal(fixedValues);The type of fixedValues is readonly [1, 2, 3]. It is a tuple because it has a fixed length and a known type at each position. A readonly tuple can be viewed as a readonly array, but it cannot be used as a mutable number[].
If TypeScript allowed this call, addTotal could call push and change a value that the caller declared readonly.
A function that only reads its input should accept a readonly type instead.
function sum(values: readonly number[]): number {
return values.reduce((total, value) => total + value, 0);
}
const fixedValues = [1, 2, 3] as const;
console.log(sum(fixedValues)); // 6
console.log(sum([4, 5, 6])); // 15The parameter readonly number[] accepts both mutable arrays and readonly arrays.
| Parameter type | Mutable array argument | Readonly array argument |
|---|---|---|
| `number[]` | Yes | No |
| `readonly number[]` | Yes | Yes |
The rule is one-way: a mutable array can be passed to a function that only reads it, but a readonly array cannot be passed to a function that might mutate it.
Readonly means “do not mutate through this reference”
The readonly modifier applies to the reference used by the function. It does not make a separate copy of the array.
function first(values: readonly string[]): string | undefined {
return values[0];
}
const names = ["Ada", "Linus"];
const result = first(names);
names.push("Grace"); // allowed
console.log(result); // AdaThe function cannot call push on values, but the original names variable is still mutable because its type is string[].
This design lets a function promise not to modify its input without forcing every caller to create a copy.
Tuples and generic functions
A readonly tuple contains more information than a general readonly array. For example, its length and element positions are known.
function describePair(pair: readonly [string, number]): string {
return `${pair[0]} has value ${pair[1]}`;
}
const pair = ["score", 42] as const;
console.log(describePair(pair)); // score has value 42The parameter is a readonly tuple, so the function can rely on two positions while still being unable to assign to either position.
For a generic function, add readonly to the constraint when the function should preserve tuples and accept readonly arrays.
function last<const T extends readonly unknown[]>(
values: T
): T[number] | undefined {
return values[values.length - 1];
}
const item = last(["id", 1] as const);
// item: "id" | 1 | undefined
console.log(item);Here, T[number] means “the union of all element types in T.” The function can read the array without giving up the tuple's literal information.
When mutation is required
Some functions intentionally modify an array. Those functions should require a mutable array and make that behavior clear in their name or documentation.
function appendRetry(values: number[], retryCount: number): void {
values.push(retryCount);
}
const mutableValues = [1, 2];
appendRetry(mutableValues, 3);
console.log(mutableValues); // [1, 2, 3]If you need to use a readonly array with such a function, create a mutable copy. The spread syntax makes a new array.
const fixedValues = [1, 2, 3] as const;
appendRetry([...fixedValues], 4);
console.log(fixedValues); // [1, 2, 3]The copy is mutable, but the original readonly tuple remains unchanged.
A common mistake: casting away readonly
You can force a readonly value into a mutable type with a type assertion, but this removes a useful safety check.
function clear(values: number[]): void {
values.length = 0;
}
const fixedValues = [1, 2, 3] as const;
clear(fixedValues as unknown as number[]);
console.log(fixedValues); // []The assertion compiles, but the function mutates the original runtime array. Prefer a copy when mutation is necessary.
The readonly modifier also applies shallowly. A readonly object can prevent reassignment of a property, but nested objects may remain mutable unless they are readonly too.
const settings = {
labels: ["one", "two"],
} as const;
// settings.labels = []; // Error
settings.labels.push("three"); // allowedThe property labels cannot be replaced, but its array is not deeply readonly in this example.
Practical decision rules
Choose the parameter type based on what the function does:
- Use
readonly T[]when the function only reads elements. - Use
readonly [A, B]when the function needs a fixed tuple shape but must not modify it. - Use
T[]when the function intentionally changes the array. - Copy a readonly array with
[...values]before passing it to a mutating API. - Do not use a type assertion merely to silence a readonly error.
- Remember that
readonlyprevents mutation through a type, not mutation through every reference.
Exercise
What parameter type should sum use if it must accept both number[] and [1, 2, 3] as const without modifying either input?
Show answer
readonly number[]. It accepts mutable and readonly arrays, and it prevents sum from calling mutating methods such as push.