Deep Copy TS

0.5.4 · active · verified Sun Apr 19

deep-copy-ts is a utility library for JavaScript and TypeScript designed to create robust deep copies (clones) of various data structures. It accurately duplicates a broad spectrum of primitive values, objects, arrays, and complex built-in types such as Date, RegExp, ArrayBuffer, DataView, and various TypedArrays (Float32Array, Int8Array, etc.). The current stable version is 0.5.4, indicating it is pre-1.0.0 and may undergo breaking changes in future minor releases. While a specific release cadence is not published, the active versioning suggests ongoing development. A key differentiator is its comprehensive handling of numerous JavaScript built-in types and its TypeScript-first approach, offering type safety and reliable deep cloning without mutating the original object.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `deepCopy` to duplicate an object containing various primitive and complex data types, including nested structures, dates, regexps, functions, and typed arrays. It then verifies that modifications to the copied object's nested properties do not affect the original object, illustrating the deep cloning behavior. It also shows that functions are copied by reference.

import { deepCopy } from 'deep-copy-ts';

const originalObject = {
  primitive: 123,
  text: 'hello world',
  nested: {
    array: [1, 2, { sub: 'item' }],
    date: new Date('2023-01-01T12:00:00Z'),
    regex: /test/gi,
  },
  func: () => console.log('This is a function'),
  nullValue: null,
  undefinedValue: undefined,
  typedArray: new Uint8Array([10, 20, 30]),
  buffer: new ArrayBuffer(8),
  dataView: new DataView(new ArrayBuffer(16))
};

const copiedObject = deepCopy(originalObject);

console.log('Original object:', originalObject);
console.log('Copied object:', copiedObject);

// Verify deep copy by modifying a nested property
copiedObject.nested.array[0] = 999;
copiedObject.nested.date.setFullYear(2050);

console.log('\nAfter modifying copiedObject:');
console.log('Original array element:', originalObject.nested.array[0]); // Should be 1
console.log('Copied array element:', copiedObject.nested.array[0]);     // Should be 999
console.log('Original date year:', originalObject.nested.date.getFullYear()); // Should be 2023
console.log('Copied date year:', copiedObject.nested.date.getFullYear());     // Should be 2050

// Functions are copied by reference
console.log('Are functions strictly equal?', originalObject.func === copiedObject.func); // true

view raw JSON →