TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

cloning object

Open dlaberge opened this issue 11 years ago • 3 comments

I have documented the question more on Stack Overflow (http://stackoverflow.com/questions/28150967/typescript-cloning-object)

Is there a way to clone an object in typescript? Currently I'm using the following hack

var cloneObj = new this.constructor();

but typescript raises the following error : error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

dlaberge avatar Feb 05 '15 18:02 dlaberge

Can you clarify exactly what the issue you're getting with your current answer is?

DanielRosenwasser avatar Feb 05 '15 22:02 DanielRosenwasser

The problem is that the compiler rises an error when I try to call a constructor dynamically.

var cloneObj = new this.constructor(); // error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

The way I found to make the compiler 1.3 happy was

var cloneObj = new (<any> this.constructor());

But that method does not work with 1.4.1.

Is there a way to call a constructor dynamically?

dlaberge avatar Feb 06 '15 13:02 dlaberge

Using your code from SO any of these casts work with the latest bits and should have on every version since:

    var cloneObj = new (<any>this.constructor());
    var cloneObj = new (<any>this.constructor)();
    var cloneObj = new (<any>this).constructor();

danquirk avatar Feb 06 '15 20:02 danquirk