What it is and why to use it
A readonly array type allows reading elements without allowing mutation through that reference. It is useful for a function that should inspect a caller’s data without sorting, pushing or replacing its elements. Mutable arrays can be passed to such a read-only parameter.
Common mistakes and limitations
Readonly types are compile-time restrictions, not Object.freeze calls. Another reference may still mutate the array, and referenced element objects are not deeply frozen. Copy elements deliberately if their internal state also needs isolation.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
function total(values: readonly number[]): number;Examples
Readonly Arrays and Mutable Copies
Standalone TypeScript 5.8+ example; expected output is explained below.
function sortedCopy(values: readonly number[]): number[] {
return [...values].sort((a, b) => a - b);
}
const original = [3, 1, 2];
console.log(sortedCopy(original).join(","));
console.log(original.join(","));- values cannot be sorted directly through its readonly type.
- Spreading into a new array creates a mutable shallow copy that sort can change.
- The original order remains 3,1,2. This is useful for presenting sorted data without altering shared application state.
- Expected output: 1,2,3 3,1,2
Best practices
- Readonly types are compile-time restrictions, not Object.freeze calls. Another reference may still mutate the array, and referenced element objects are not deeply frozen. Copy elements deliberately if their internal state also needs isolation.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook