👯 Creates a fast deep clone of supported values, with circular reference support.
The following types are supported for deep cloning:
Primitive types (except Symbols)
Plain Objects
Arrays
Maps & Sets
Dates
RegExps (lastIndex is not preserved)
RegExps (including
lastIndex)Errors
ArrayBuffers & TypedArrays
DataViews
Circular References: Correctly handles circular references by keeping track of cloned objects.
Functions and unsupported object instances are preserved by reference. If you need a generic platform clone for transferable objects, DOM/web APIs, or other specialized instances, use native structuredClone().
Supported Error values preserve name, message, stack, cause, and custom own enumerable properties. Nested supported cause values are cloned deeply.
Syntax
import { clone } from '@opentf/std'; clone<T>(val: T): T
Parameters
val: The value to deeply clone.
Returns
A deep clone of supported values. Unsupported object instances and functions are returned by reference.
Examples
const input = { arr: [1, 2, 3], obj: { a: 'abc', b: 123 }, date: new Date(), map: new Map([['a', 1], ['b', 2]]) }; const output = clone(input); input === output; // false output.arr === input.arr; // false output.obj === input.obj; // false output.map === input.map; // false output.date.getTime() === input.date.getTime(); // true class Box { constructor(value) { this.value = value; } } const boxed = new Box(1); const clonedBoxed = clone({ boxed }); clonedBoxed.boxed === boxed; // true // Circular references const circular: any = { a: 1 }; circular.self = circular; const clonedCircular = clone(circular); clonedCircular.self === clonedCircular; // true