Deeply freeze object

This commit is contained in:
2026-08-10 02:30:55 +00:00
parent a075594683
commit 78311487a4
4 changed files with 94 additions and 7 deletions
+25
View File
@@ -0,0 +1,25 @@
import { DeeplyReadonly } from "./types";
/**
* Recursively freezes an object by iterating over all properties and freezing them.
* @param obj - The object to freeze.
* @returns The frozen object.
*/
export const deepFreeze = <T>(value: T): DeeplyReadonly<T> => {
if (
value !== null &&
(typeof value === 'object' || typeof value === 'function')
) {
for (const key of Reflect.ownKeys(value)) {
const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
if (descriptor && 'value' in descriptor) {
deepFreeze(descriptor.value);
}
}
Object.freeze(value);
}
return value;
}