Typescript: cloning object

Created on 5 Feb 2015  路  3Comments  路  Source: microsoft/TypeScript

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.

Question

Most helpful comment

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();

All 3 comments

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

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?

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();
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Zlatkovsky picture Zlatkovsky  路  3Comments

blendsdk picture blendsdk  路  3Comments

wmaurer picture wmaurer  路  3Comments

rigdern picture rigdern  路  3Comments

manekinekko picture manekinekko  路  3Comments