@metreeca/core - v0.9.19
    Preparing search index...

    Function immutable

    Creates an immutable deep clone, optionally validating against a type guard.

    • Creates an immutable deep clone.

      Values are processed according to their type:

      • Cloned and frozen: plain objects and arrays; nested structures are cloned recursively; accessor properties are preserved as read-only (getters only, setters removed)
      • Returned as-is: primitives, functions, and non-plain objects (for example, Date, Map, Set, class instances, or objects with null prototype)

      This function is idempotent at every depth: every cloned object and array is branded internally, so calling it again on a frozen clone, or on any nested member extracted from one, returns the same reference. Members reached through multiple paths, or extracted and re-nested into another structure, keep a stable identity. This makes it safe and efficient to use defensively.

      Caution

      Circular references are not supported. Do not pass objects with cycles.

      Type Parameters

      • T

        The type of the value to be cloned

      Parameters

      • value: T

        The value to make immutable

      Returns T

      A deeply frozen clone of value

      Stack overflow when value contains circular references

    • Creates an immutable deep clone, validating against a type guard.

      Values are processed according to their type:

      • Cloned and frozen: plain objects and arrays; nested structures are cloned recursively; accessor properties are preserved as read-only (getters only, setters removed)
      • Returned as-is: primitives, functions, and non-plain objects (for example, Date, Map, Set, class instances, or objects with null prototype)

      Validates value against the guard before freezing:

      • Plain objects and arrays: memoizes validation; subsequent calls with the same guard skip re-validation and return the same reference; calls with a different guard trigger revalidation and rebranding
      • Other values: validated on every call

      The guard brands only the top-level clone; nested members carry the default brand, so they remain stable under guard-less immutable calls while a guarded call on a nested member revalidates it.

      Caution

      Circular references are not supported. Do not pass objects with cycles.

      Important

      Guards must have stable identity. Use module-level named functions or const lambdas.

      Type Parameters

      • T

        The validated type of the returned clone

      Parameters

      • value: unknown

        The value to make immutable

      • guard: Guard<T>

        Type guard function to validate value

      • Optionalmessage: string

        Optional error message when validation fails

      Returns T

      A deeply frozen clone of value, branded with the guard

      When the guard returns false

      Stack overflow when value contains circular references