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?