The type of the value to freeze
The value to deeply freeze.
Internalvisited: WeakSet<object> = ...Internal WeakSet used to track visited objects during recursion.
The same value, deeply frozen and typed as Readonly<T>
This function performs a deep, immutable freeze:
WeakSet internally to avoid memory leaksconst config = deepFreeze({
api: {
url: 'https://example.com',
timeout: 5000
}
});
// Compile-time error and runtime TypeError
config.api.url = 'https://evil.com';
const list = deepFreeze([1, 2, { value: 3 }]);
// Runtime TypeError
list.push(4);
// Runtime TypeError
list[2].value = 10;
const obj: any = { name: 'circle' };
obj.self = obj;
// Does not throw or recurse infinitely
deepFreeze(obj);
// Runtime TypeError
obj.name = 'x';
const shared = { count: 0 };
const state = deepFreeze({
a: shared,
b: shared
});
// Runtime TypeError
state.a.count = 1;
// Runtime TypeError
state.b.count = 2;
const secret = Symbol('secret');
const obj = {};
Object.defineProperty(obj, 'hidden', {
value: { token: '123' },
enumerable: false
});
(obj as any)[secret] = { enabled: true };
deepFreeze(obj);
// Runtime TypeError
obj.hidden.token = '456';
// Runtime TypeError
(obj as any)[secret].enabled = false;
Recursively freezes an object and all of its nested properties.