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.
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.
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.
#programming #js #typescript #web-development #javascript