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?
The simple way to do this would be with getters that return static values and setters that throw errors.
let obj = {
get a() {
return 1;
},
set a(val) {
throw new Error('Can\'t set a');
},
get b() {
return 2;
},
set b(val) {
throw new Error('Can\'t set b');
}
};
obj.c = 3; // works
console.log(obj);
obj.a = 4; // throws an error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With