Typescript
Readonly
Typescript supports the readonly
attribute.
Assume the following function to sort arrays:
function sortNumbers(array: Array<number>) {
return array.sort((a, b) => a - b)
}
const numbers = [7, 3, 5]
const sortedNumbers = sortNumbers(numbers)
console.log(sortedNumbers)
console.log(numbers)
We can see that the function sortNumbers
changed both arrays.
We can add the Readonly
type, but this alone won’t work.
The array still needs to be changed in place and this will generate an error.
function sortNumbers(array: Readonly<Array<number>>) {
return array.sort((a, b) => a - b)
}
By doing a defensive copy of the array, this will work:
function sortNumbers(array: Readonly<Array<number>>) {
return [...array].sort((a, b) => a - b)
}