Enforce immutability or partial immutability that doesn't fail silently

Viewed 76

Is there a way to enforce partial immutability on an object that will throw an error if someone tries to mutate it?

For example, let obj = {a: 1, b: 2} and I want obj.a and obj.b to be immutable but to still allow more keys to be added to obj, i.e to allow obj.c = 3.

I thought of nesting properties in sub-objects and using Object.freeze like so:

let obj = {subObj:{a: 1, b:2}}; 
Object.freeze(obj.subObj);

But it appears that it fails silently afterward, i.e obj.subObj.a = 3 doesn't mutate a but doesn't give any indication of a problem either. Is there a way to force it to throw an error?

3 Answers
Related