I want to have a function which returns an Array, but I want the returned Array to be readonly, so I should get a warning/error when I try to change its contents.
function getList(): readonly number[] {
return [1,2,3];
}
const list = getList();
list[2] = 5; // This should result in a compile error, the returned list should never be changed
Can this be achieved in TypeScript?
Readonly<number[]>
. I can no longer usefor...of
, saying that type must have a method that returns an iterator. – Interlopea => Object.freeze(a);
which turns thea
array into shallow immutable. Attempting to change or delete it's items seems throw a "Type Error" in strict mode but fails silenty otherwise. If any one of the items is a reference type then it will remain mutable unless you freeze them i.e. recursively. – Einstein