TypeScript return immutable/const/readonly Array
This seems to work...
function getList(): ReadonlyArray<number> {
return [1, 2, 3];
}
const list = getList();
list[0] = 3; // Index signature in type 'ReadonlyArray<number>' only permits reading.
Try it in the Playground
ReadonlyArray<T>
is implemented like this:
interface ReadonlyArray<T> {
readonly [n: number]: T;
// Rest of the interface removed for brevity.
}
The very code from OP now works since TypeScript 3.4 introduced a new syntax for ReadonlyArray
:
While it's good practice to use
ReadonlyArray
overArray
when no mutation is intended, it's often been a pain given that arrays have a nicer syntax. Specifically,number[]
is a shorthand version ofArray<number>
, just asDate[]
is a shorthand forArray<Date>
.TypeScript 3.4 introduces a new syntax for
ReadonlyArray
using a newreadonly
modifier for array types.
This code now works as expected:
function getList(): readonly number[] {
return [1,2,3];
}
const list = getList();
list[2] = 5; // <-- error
Playground.