Sub topic 6
Passing readonly values to functions
After as const, a value is no longer a plain mutable array or object. This chapter covers what that does to function calls. You will see why a readonly tuple is rejected by some signatures and accepted by others, how to write signatures that accept both, and where TypeScript's readonly checking has gaps.
What this chapter assumes
You should already know:
- How
as constturns an array literal into a readonly tuple and an object literal into an object withreadonlyliteral-typed properties. - How to write a function with typed parameters and a generic function with
<T>. - That
readonlyin a type means "this reference cannot be used to write", not "the data is frozen".
The problem: a readonly tuple is rejected
Here is a function that only reads its input, and the error you get when you pass it a const-asserted array:
function sum(nums: number[]): number {
return nums.reduce((total, n) => total + n, 0);
}
const xs = [1, 2, 3] as const; // readonly [1, 2, 3]
// sum(xs);
// error: The type 'readonly [1, 2, 3]' is 'readonly' and cannot be
// assigned to the mutable type 'number[]'.The message is accurate. A parameter of type number[] tells the compiler that the function may call push, pop, sort, or assign to nums[0]. The tuple promised that nobody would do any of that, so the compiler refuses to hand it over.
sum never mutates anything, so the signature is wrong, not the call. The signature claims more permission than the function uses.
Fix the signature, not the call site
Declare the parameter as readonly number[]:
function sumReadonly(nums: readonly number[]): number {
return nums.reduce((total, n) => total + n, 0);
}
const xs = [1, 2, 3] as const;
const ys: number[] = [4, 5, 6];
console.log(sumReadonly(xs)); // 6
console.log(sumReadonly(ys)); // 15Both calls compile. readonly number[] means "a function that receives this value will only read it", and both a mutable array and a readonly tuple meet that condition.
The readonly modifier on array types has an equivalent generic spelling:
function sumAlt(nums: ReadonlyArray<number>): number {
return nums.reduce((total, n) => total + n, 0);
}readonly number[] and ReadonlyArray<number> are the same type. Pick one and use it consistently in a codebase. The readonly T[] form is shorter.
What a readonly array type removes
ReadonlyArray<T> is not the same interface as Array<T> with a flag set. It is a smaller interface that omits the mutating methods.
| Operation | `number[]` | `readonly number[]` |
|---|---|---|
| `xs[0]`, `xs.length` | allowed | allowed |
| `map`, `filter`, `reduce`, `slice`, `concat` | allowed | allowed |
| `includes`, `indexOf`, `find`, `join` | allowed | allowed |
| `push`, `pop`, `shift`, `unshift`, `splice` | allowed | not available |
| `sort`, `reverse`, `fill`, `copyWithin` | allowed | not available |
| `xs[0] = value` | allowed | error: read-only index signature |
The sort and reverse entries often surprise people. They mutate in place, so they are missing from the readonly type. To sort a readonly array, copy it first:
const ROLES = ["viewer", "admin", "editor"] as const;
const sorted = [...ROLES].sort();
// string-compatible array: ("viewer" | "admin" | "editor")[]
console.log(sorted); // ["admin", "editor", "viewer"]Recent TypeScript libraries also include toSorted and toReversed. These return a new array and exist on readonly arrays, provided your lib setting targets a recent enough ECMAScript version.
The assignability rule
The relationship is one-directional. Any mutable array can be used where a readonly array is expected, but not the other way around. The reason is that readonly T[] offers a subset of what T[] offers, so T[] is the more capable type, and a more capable value can stand in for a less capable one.
The dotted arrow is the failing case from the start of the chapter. In everyday terms:
- A parameter typed
readonly T[]accepts every array and tuple, mutable or not. - A parameter typed
T[]accepts only mutable arrays and tuples.
So the guideline is: if a function does not modify an array parameter, type it as readonly. This costs callers nothing and removes the friction with as const values. Libraries that type their inputs as mutable arrays force their users to copy or cast.
Tuples keep their length and positions
A readonly tuple has fixed length and positional types, and those must still match. Widening element types is fine. Changing the length is not.
const point = [10, 20] as const; // readonly [10, 20]
function lengthOf(p: readonly [number, number]): number {
return Math.hypot(p[0], p[1]);
}
function lengthOf3(p: readonly [number, number, number]): number {
return Math.hypot(p[0], p[1], p[2]);
}
console.log(lengthOf(point)); // 22.360679...
// lengthOf3(point);
// error: Source has 2 element(s) but target requires 3.readonly [10, 20] is assignable to readonly [number, number] because each literal type is a subtype of number. It is also assignable to readonly number[], because a tuple is a more specific kind of array. It is not assignable to a tuple of a different length.
If the function should accept any length, use readonly number[]. If the length carries meaning, such as a coordinate pair, use a readonly tuple type. Then the compiler checks the length for you.
Generic functions keep the literal types
The signature readonly T[] also works well with generics. When the argument is a const tuple, T is inferred as the union of its element types:
const ROLES = ["admin", "editor", "viewer"] as const;
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const r = first(ROLES);
// "admin" | "editor" | "viewer" | undefinedThe result is the union of all three literals, not "admin", because readonly T[] treats the tuple as an array of one element type. The compiler no longer tracks which position holds which value.
If you want to keep positional information, capture the whole array type with a constrained type parameter:
const ROLES = ["admin", "editor", "viewer"] as const;
function lastOf<T extends readonly unknown[]>(items: T): T[number] | undefined {
return items[items.length - 1] as T[number] | undefined;
}
function head<T extends readonly [unknown, ...unknown[]]>(items: T): T[0] {
return items[0];
}
const h = head(ROLES); // "admin"
const l = lastOf(ROLES); // "admin" | "editor" | "viewer" | undefinedhead requires a non-empty tuple type (readonly [unknown, ...unknown[]]) and returns T[0], which for ROLES is exactly "admin". Use T extends readonly unknown[] whenever you want the function to accept readonly tuples and keep their precise type. Writing T extends unknown[] brings back the rejection from the start of the chapter.
Objects: `readonly` properties are not checked the same way
Arrays and tuples are protected by the missing methods. Object properties are different. TypeScript does not consider readonly on a property when checking assignability.
const origin = { x: 0, y: 0 } as const; // { readonly x: 0; readonly y: 0 }
function moveRight(p: { x: number; y: number }): void {
p.x += 1;
}
moveRight(origin); // compiles without error
console.log(origin.x); // 1 at runtime, although the type says 0This compiles even though origin is declared readonly and the function writes to it. The type system lets a { readonly x: 0 } flow into { x: number }. The type of origin.x is still 0, so after the call the compiler believes a value that is now wrong at runtime.
You can protect yourself on the function side by declaring the parameter with Readonly<T> or readonly properties. This makes the function's own body fail to compile if it tries to write:
interface Point {
x: number;
y: number;
}
function distance(p: Readonly<Point>): number {
// p.x = 0; // error: Cannot assign to 'x' because it is a read-only property.
return Math.hypot(p.x, p.y);
}
console.log(distance({ x: 3, y: 4 })); // 5Readonly<Point> is a shallow wrapper. It marks the top-level properties readonly but does not affect nested objects or arrays inside them. For nested data, either mark the nested types readonly yourself or use a recursive helper type.
Escaping the restriction
Sometimes you must call a function you do not control, and it takes a mutable array. You have three options, from best to worst.
- Copy the array. The copy is mutable, and the original stays untouched.
- Ask for a fix upstream if the function does not mutate its input. Typing a read-only parameter as mutable is a bug in the signature.
- Cast only when you are certain the function does not write.
function legacyTotal(values: number[]): number {
return values.reduce((a, b) => a + b, 0);
}
const prices = [5, 10, 15] as const;
console.log(legacyTotal([...prices])); // 30Spreading creates a new array each call. For small arrays this cost is negligible. For large arrays in hot loops, measure before deciding.
Return types: do not return readonly values you want callers to change
The same reasoning applies to what you return. If a function returns readonly string[], the caller cannot push to the result without a copy. That is the point when you are exposing internal state, but it is an irritation when you build a fresh array.
const DEFAULT_TAGS = ["new", "draft"] as const;
// Exposes a shared constant: readonly is the honest return type.
function defaultTags(): readonly string[] {
return DEFAULT_TAGS;
}
// Builds a fresh array: return the mutable type.
function withTag(tag: string): string[] {
return [...DEFAULT_TAGS, tag];
}
const tags = withTag("urgent");
tags.push("extra");
console.log(tags); // ["new", "draft", "urgent", "extra"]A simple rule: return readonly when you hand back something you keep a reference to, and return the mutable type when the caller owns the result.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "The type 'readonly [...]' is 'readonly' and cannot be assigned to the mutable type" | The parameter is typed `T[]` | Change the parameter to `readonly T[]` if the function does not write |
| "Property 'push' does not exist on type 'readonly [...]'" | Mutating a readonly array | Copy first with `[...xs]` or build a new array |
| "Source has 2 element(s) but target requires 3" | Tuple length mismatch | Use a readonly array type, or fix the tuple |
| A readonly object gets modified anyway | Property `readonly` is ignored by assignability | Type the parameter as `Readonly<T>`, and freeze at runtime if needed |
| Generic result is a wide union, not one literal | `readonly T[]` erases positions | Use `T extends readonly unknown[]` and index into `T` |
Summary of the rules
- Type read-only parameters as
readonly T[]orReadonlyArray<T>. That accepts both mutable and readonly arguments. - Mutable arrays can go anywhere a readonly array is expected. The reverse is an error.
- Tuple length and positions are enforced even for readonly tuples.
- Use
T extends readonly unknown[]in generics so const tuples stay accepted and precise. - Property
readonlyon objects does not block assignment into mutable parameter types, so rely onReadonly<T>in the function signature and onObject.freezewhen you need runtime protection.
Exercise
The function below fails to compile when called with NAMES. Explain why, then rewrite the signature so that both NAMES and a plain string[] are accepted, without changing the function body.
const NAMES = ["Ada", "Grace", "Linus"] as const;
function shout(names: string[]): string {
return names.map((n) => n.toUpperCase()).join(", ");
}
shout(NAMES);
Show answer
NAMES has the type readonly ["Ada", "Grace", "Linus"], and a readonly tuple cannot be assigned to the mutable type string[], because a string[] parameter would allow the function to call push or assign to an index. shout only reads its input (map and join do not mutate), so the signature should be function shout(names: readonly string[]): string. After that change, both shout(NAMES) and shout(["a", "b"]) compile.
Exercise
Given const ROLES = ["admin", "editor", "viewer"] as const;, write a generic function pick that takes a readonly tuple and an index i of type number, and returns the element at that index. What is the return type when you call pick(ROLES, 1)? Then say whether the compiler can tell the result is "editor".
Show answer
One correct version is function pick<T extends readonly unknown[]>(items: T, i: number): T[number] { return items[i] as T[number]; }. The return type for pick(ROLES, 1) is "admin" | "editor" | "viewer". The compiler cannot tell the result is "editor", because the index parameter is typed number, not the literal 1. To keep the exact element you would need the index as a generic literal type, for example <T extends readonly unknown[], I extends number>(items: T, i: I): T[I].