Lessons · TypeScript · readonly
Promise not to change it
readonly on a property or readonly T[] on an array makes mutation a compile error.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
State that must not be mutated (React, Redux, shared config) is protected by the compiler instead of by hope.
How to think about it
Should this function be able to change its input? Type inputs as readonly when the function should not change them. Build new values with spread, map, toSorted.
Worked example
function top(xs: readonly number[]): number[] {Promise: xs is not touched.return [...xs].sort((a, b) => b - a).slice(0, 3);Copy first; sort would be an error on xs.
}
Your turn
Make the input array read-only.
function total(xs: number[]): number { return xs.reduce((a, b) => a + b, 0); }Solve one with the compiler running
The trap
readonly is shallow: readonly {a: number}[] stops replacing items but not changing a on one of them.
Practise readonly on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.