rtfeldman / seamless-immutable

Immutable data structures for JavaScript which are backwards-compatible with normal JS Arrays and Objects.
BSD 3-Clause "New" or "Revised" License
5.36k stars 194 forks source link

throw error or warn when attempting to set property on immutable object #216

Closed Lokua closed 5 years ago

Lokua commented 7 years ago
const obj = Immutable({ a: 1 })
obj.a = 2
obj.a // => 1

This is desired, of course, but goes by completely unnoticed - even in dev. What do you think about adding a set trap or perhaps using a different implementation of Object.freeze in development that would warn when attempting to set directly?

tomByrer commented 7 years ago

I like the idea, but concerned about performance in production. Could dev have a temporary wrapper / Proxy ?

svieira commented 7 years ago

Just a thought. If it's possible to wrap your code in a "use strict" context you can get the behavior you want as attempting to mutate a frozen object already causes an error in strict mode:

> !function() { "use strict"; Object.freeze({x: 1, y: 2}).x = 3; }()
VM286:1 Uncaught TypeError: Cannot assign to read only property 'x' of object '#<Object>'
crudh commented 5 years ago

I'll close this since strict mode fixes the issue and throws an error.