Hacker News new | ask | show | jobs
by orta 2514 days 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[]'.
1 comments

Well, 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.