cloneDeep() function
Creates a deep clone of value.
Supported types: primitives, Array, plain objects (including Object.create(null)), Date, RegExp (lastIndex preserved), Map, Set, ArrayBuffer, TypedArray, and DataView. Class instances are cloned with their prototype preserved and own enumerable properties (string and symbol keys) copied. Circular references are supported.
Unlike structuredClone, functions are kept by reference instead of throwing, and prototypes of class instances are preserved. WeakMap/WeakSet/Promise cannot be cloned and are returned as-is.
Signature:
typescript
declare function cloneDeep<T>(value: T): T;Example
ts
const obj = { a: 1, b: { c: 2 }, d: [1, 2, 3] };
const cloned = cloneDeep(obj);
cloned.b === obj.b; // false
cloned.d === obj.d; // false
// circular references
const circular = { a: 1, self: null as unknown };
circular.self = circular;
const clonedCircular = cloneDeep(circular);
clonedCircular.self === clonedCircular; // true
// class instances keep their prototype
class Point {
constructor(public x: number) {}
}
cloneDeep(new Point(1)) instanceof Point; // true