JS Utils Kit
    Preparing search index...

    Function deepFreeze

    • Recursively freezes an object and all of its nested properties.

      Type Parameters

      • T

        The type of the value to freeze

      Parameters

      • obj: T

        The value to deeply freeze.

      • Internalvisited: WeakSet<object> = ...

        Internal WeakSet used to track visited objects during recursion.

      Returns Readonly<T>

      The same value, deeply frozen and typed as Readonly<T>

      This function performs a deep, immutable freeze:

      • Safely handles circular references
      • Freezes symbol and non-enumerable properties
      • Prevents repeated processing of shared references
      • Uses WeakSet internally to avoid memory leaks
      const 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;
      function task() {}
      (task as any).meta = { active: true };

      deepFreeze(task);

      // Runtime TypeError
      (task as any).meta.active = false;