Readonly arrays
Concept and syntax
readonly number[] and ReadonlyArray<number> describe an array view that can be read but not mutated through that reference. Methods such as push are unavailable and index assignment is rejected. A mutable array can be passed to a function accepting a readonly view; the original owner can still change it. This is a static restriction, not a frozen runtime object.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
const original = [2, 4];const view: readonly number[] = original;original.push(6);console.log(view[0], view.length);Expected output (one line per log):
2 3Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
Expected compiler diagnostic: TS2339. The readonly view has no push method. Make a new mutable copy if editing is intended.
Practice and recap
Create a readonly view and mutable alias of an array. Change the alias and read the view; then try changing the view directly.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Readonly arrays — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which operation is allowed through a readonly number[]?
Does a readonly view prevent the original mutable alias from changing?
Which operation works through this readonly view?
const view: readonly number[] = [2, 4];view.push(6);