Deep cloning Entity instances in Typescript? Deep cloning Entity instances in Typescript? typescript typescript

Deep cloning Entity instances in Typescript?


If you duplicate an object with the spread operator, your new object won't be an instance of a class, but a literal object with no type, so it won't be a real clone of the existing object.

If the objects you want to clone are defined by you (not an external library) you could do something like:

export function deepClone(array: any[]): any[] {  return array.map((e:any) => (new e.constructor(e)));}

And then in your classes meant to be cloned:

constructor(obj: any) {   Object.assign(this, obj);}


I use this method

https://stackblitz.com/edit/typescript-qmzgf7

const clone = obj =>  Array.isArray(obj)    ? obj.map(item => clone(item))    : obj instanceof Date      ? new Date(obj.getTime())      : (typeof obj === 'object') && obj        ? Object.getOwnPropertyNames(obj).reduce((o, prop) => ({ ...o, [prop]: clone(obj[prop]) }), {})        : obj;

It doesn't work for all JavaScript object you might encounter, but it will likely work for anything that comes from a server call in JSON format.


In regards to your actual implementation, you should consider using old mate JSON to help you out with this.

var array:Array<number> = [1,2,3];var deepClone = clone(array);deepClone[0] = 99;console.log({ array, deepClone });  // returns [1,2,3] & [99,2,3]function clone<T>(array:T[]) {return JSON.parse(JSON.stringify(array)) as Array<T>;}