3 ms·
TypeScript does a pretty good job here if you're willing to add a bit of extra syntax: const a = [1,2,3] a.push(4) const b: readonly number[] = [1,2,3]
by orta 7y ago
TypeScript does a pretty good job here if you're willing to add a bit of extra syntax:
const a = [1,2,3]
a.push(4)
const b: readonly number[] = [1,2,3]
b.push(4) // Property 'push' does not exist on type 'readonly number[]'.
- rndgermandude 7y agoWell, Object.freeze in plain JS can help too. > Object.freeze([1,2,3]).push(4) TypeError: can't define array index property past the end of an array with non-writable length (firefox) Uncaught TypeError: Cannot add property 3, object is not extensible (chrome) Of course, it will only blow up at runtime. But better than not blowing up at all, creating heisenbugs and such. I often find myself writing classes where the last step of a constructor is to Object.freeze (or at least Object.seal) itself.