How to dynamically clone object trees in TypeScript without errors?

How can I dynamically clone an object tree in TypeScript, given a superclass and its subclasses?

I have a superclass Entity that serves as the parent for various subclasses such as Customer, Product, and ProductCategory. For example:

var cust: Customer = new Customer(); cust.name = “someName”; cust.products.push(new Product(someId1)); cust.products.push(new Product(someId2));

I created a clone function in the Entity class to clone the entire object tree: public clone(): any { var cloneObj = new this.constructor(); for (var attribut in this) { if (typeof this[attribut] === “object”) { cloneObj[attribut] = this.clone(); } else { cloneObj[attribut] = this[attribut]; } } return cloneObj; }

However, I encounter the following TypeScript error when transpiled to JavaScript: error TS2351: Cannot use ‘new’ with an expression whose type lacks a call or construct signature.

Although the script works, I want to eliminate the transpiled error. What is the correct approach to achieve this typescript copy object functionality without causing errors?

Hello Mehta_Tvara,

Using structuredClone:

Properties: Yes Methods: Yes Deep Copy: Yes

const clone = structuredClone(customer);

structuredClone is a native method in modern JavaScript for deep cloning objects, but it may need polyfills for older environments.

Hey Mehta,

Using a Library for Deep Cloning:

Properties: Yes Methods: Yes Deep Copy: Yes Install a deep cloning library, like lodash: npm install lodash Use the library for cloning: import _ from ‘lodash’;

const clone = _.cloneDeep(customer);

_.cloneDeep from lodash handles deep cloning and preserves methods, but requires adding an external dependency.