Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cloning object #1946

Closed
dlaberge opened this issue Feb 5, 2015 · 3 comments
Closed

cloning object #1946

dlaberge opened this issue Feb 5, 2015 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@dlaberge
Copy link

dlaberge commented Feb 5, 2015

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.

@DanielRosenwasser DanielRosenwasser added the Question An issue which isn't directly actionable in code label Feb 5, 2015
@DanielRosenwasser
Copy link
Member

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

@dlaberge
Copy link
Author

dlaberge commented Feb 6, 2015

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?

@danquirk
Copy link
Member

danquirk commented Feb 6, 2015

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

@mhegazy mhegazy closed this as completed Apr 21, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants