跳到主要内容

deepFreeze

TS JS Deno

Deep freezes an object.

Use Object.keys() to get all the properties of the passed object, Array.prototype.forEach() to iterate over them. Call Object.freeze(obj) recursively on all properties, checking if each one is frozen using Object.isFrozen() and applying deepFreeze() as necessary. Finally, use Object.freeze() to freeze the given object.

typescript
const deepFreeze = <T extends object>(obj: T) => {
Object.keys(obj).forEach((prop) => {
if (
typeof obj[prop as keyof T] === 'object' &&
!Object.isFrozen(obj[prop as keyof T])
) {
deepFreeze(obj[prop as keyof T]);
}
});
return Object.freeze(obj);
};
typescript
const o = deepFreeze([1, [2, 3]]);

o[0] = 3; // not allowed, TypeError: Cannot assign to read only property '0' of object '[object Array]'
o[1][1] = 4; // not allowed as well, TypeError: Cannot assign to read only property '1' of object '[object Array]'