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

Roam-Cooper picture Roam-Cooper  路  3Comments

DanielRosenwasser picture DanielRosenwasser  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

zhuravlikjb picture zhuravlikjb  路  3Comments