David Laberge David Laberge - 4 months ago 376
TypeScript Question

typescript - cloning object

I have a super class that is the parent (

Entity
) for many subclass (
Customer
,
Product
,
ProductCategory
...)

I'm looking to clone dynamically an object that contains different sub objects in Typescript.

In example : a
Customer
that has different
Product
who has a
ProductCategory


var cust:Customer = new Customer ();

cust.name = "someName";
cust.products.push(new Product(someId1));
cust.products.push(new Product(someId2));


In order to clone the whole tree of object I created a function in
Entity


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;
}


The
new
rises the following error when it is transpiled to javascript:
error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.


Although the script works, I would like to get rid of the transpiled error

Answer

You can use a type assertion to tell the compiler that you know better:

public clone(): any {
    var cloneObj = new (<any>this.constructor());
    for (var attribut in this) {
        if (typeof this[attribut] === "object") {
            cloneObj[attribut] = this.clone();
        } else {
            cloneObj[attribut] = this[attribut];
        }
    }
    return cloneObj;
}
Comments