Skip to content

Function: cloneDeep() ​

cloneDeep<T>(value): T

Deep clone a value. The primitives (undefined, null, numbers, strings…) and the functions are returned as they are. The objects and arrays are copied with their prototype (a class instance stays an instance of its class), their symbol and non-enumerable properties, and their circular references (an object containing itself gives a clone containing the clone). An own getter is called: the clone has a data property holding the clone of the value it returns (a getter computed from the other properties no longer follows them); an own setter without getter is copied as it is. Buffers, typed arrays, array buffers, data views, dates, regular expressions, URLs, errors (with their stack), boxed primitives, maps and sets (their values cloned, the keys of the maps kept) are cloned as such, and a proxy is cloned as the object it exposes. A frozen, sealed or non-extensible object or array gives a clone frozen, sealed or non-extensible as well.

Kept as they are, not cloned: a WeakMap or WeakSet (its entries cannot be enumerated), a Promise (its state cannot be copied), and an object whose prototype has a truthy isImmutable property. Not cloned faithfully: an object with internal slots not listed above gives an object of its prototype without its internal state, whose methods throw.

Type Parameters ​

T ​

T

Parameters ​

value ​

T

The value to clone, of any type.

Returns ​

T

The clone, of the value's type.

Example ​

typescript
import {cloneDeep} from 'lakutata/utils'

const settings: {retries: number, hosts: string[]} = {retries: 3, hosts: ['a', 'b']}
const copy: {retries: number, hosts: string[]} = cloneDeep(settings)
copy.hosts.push('c')
console.log(settings.hosts, copy.hosts)
//['a', 'b'] ['a', 'b', 'c']

Released under the MIT License.