Everything in JavaScript world is an Object. We often need to clone an Object, and when working with TypeScript, preserve the object type may also be required. This article will explore the options of deep clone an Object with TypeScript, and implement the clone functionality without dependencies to external libraries.

Shallow copy

A shallow copy using Object.Assign or Spread operator will duplicate the top-level properties, but the properties as an Object is copied as a reference, thus it is shared between the original source and target(copied Object).

const objShallowCopy = Object.assign({}, Obj1);
// or
const objShallowCopy = {...Obj1};

Although the above methods can not deep clone a complex Object properly, it is good enough for some cases that nested object properties are not required.

Simplest way to do a Deep copy

Using JSON.parse and JSON.stringify is the simplest way to deep clone an Object. With the one line code below, the nested properties of a complex object can be deep cloned.

const objCloneByJsonStringfy = JSON.parse(JSON.stringify(Obj1));

But it does has a few caveats.

  • It is slow due to the natural of the method involving serialization and deserialization of an Object to and from JSON. When clone an large object using this method, performance will be a concern.
  • Dates type is not supported. Dates will be parsed as Strings, thus the Dates object in source object will be lost after copy.
  • It does not preserve the type of the object as well as the methods. As the code snippet below shows, the instanceof return false, because it can not find the constructor in the Object’s prototype chain. And the functions within source Object will be missing after copy.

#programming #js #typescript #web-development #javascript

Deep clone an Object and preserve its type with TypeScript
23.50 GEEK