TypeScript Reference ยท Primitive and Special Types
TypeScript readonly arrays
Reference for TypeScript read-only arrays: readonly T[], ReadonlyArray<T>, which methods remain, assignability rules, as const and why it is compile-time only.
A readonly T[] is an array type that removes all mutating methods: push, pop, splice, sort, reverse and index assignment are not available. Reading, map, filter, slice, concat and iteration all still work, because they return new values.
ReadonlyArray<T> is the same type spelled generically. Use it for function parameters that only read the list, for constants, and for data you share between modules. The protection exists only at compile time: at runtime the array is a normal, mutable JavaScript array unless you also Object.freeze it.
const days: readonly string[] = ["Mon", "Tue"]; // days.push("Wed"); // error
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
let a: readonly T[]; let b: ReadonlyArray<T>; let c: readonly [A, B]; // readonly tuple const d = [1, 2] as const; // readonly [1, 2]
| Part | Description |
|---|---|
readonly T[] |
Array type without mutating members. |
ReadonlyArray<T> |
Same type; the older spelling. |
readonly [A, B] |
Read-only tuple. |
as const |
Makes an array literal a readonly tuple of literal types. |
Edge cases:
readonlyis only allowed on array and tuple types in this position. You cannot writereadonly Array<T>; useReadonlyArray<T>.- A mutable array is assignable to a readonly one, but not the other way round, because the readonly reference could be used to hide mutation.
- The array itself may still change through another, mutable reference.
- Elements that are objects are not made read-only; only the array structure is. Use
Readonly<T>on the elements as well.
Usage notes
- Accept readonly, return mutable-or-readonly deliberately. Parameters typed
readonly T[]accept both kinds of array, so they are the more flexible choice for callers. - Compile-time only.
Object.freezegives a runtime guarantee and also types its result as readonly. - Non-mutating alternatives.
toSorted,toReversed,toSplicedandwith(ES2023) return copies and are available on readonly arrays. as constand unions.(typeof levels)[number]turns a constant list into a union of its values.- Errors from
.sort(). Sorting mutates, soreadonlyarrays reject it. Copy first with[...xs].sort()or usetoSorted. - Generic constraints.
T extends readonly unknown[]matches both mutable and readonly arrays and tuples.