To make an array immutable or read-only, one of the straightforward ways to achieve is to use the as const
syntax after the array itself in TypeScript.
TL;DR
// array of numbers
// the array is now immutable or readonly
const numsArr = [1, 2, 3, 4, 5] as const;
// try assigning a value to the 0th index
numsArr[0] = 6; // ❌ Error. Cannot assign to '0' because it is a read-only property.
For example, let's say we have an array of numbers like this,
// array of numbers
const numsArr = [1, 2, 3, 4, 5];
Now let's make the above numsArr
array immutable or read-only using the as const
syntax after array itself.
It can be done like this,
// array of numbers
// the array is now immutable or readonly
const numsArr = [1, 2, 3, 4, 5] as const;
The array is now immutable.
Now let's try to assign a new value to the 0th
index of the array like this,
// array of numbers
// the array is now immutable or read-only
const numsArr = [1, 2, 3, 4, 5] as const;
// try assigning a value to the 0th index
numsArr[0] = 6; // ❌ Error. Cannot assign to '0' because it is a read-only property.
As you can see the TypeScript compiler doesn't allow assigning a new value and shows an error saying Cannot assign to '0' because it is a read-only property
which is what we need to happen.
We have successfully made the array immutable or read-only. Yay 🥳!
See the above code live in codesandbox.
That's all 😃!