0

how to create an object based on the type of another object in TypeScript

obj1 = new Object();

obj2 = new "obj1.constructor.name"

I have to do like that because Object 1 can have different class .

3
  • 3
    new obj1.constructor() should work. BTW this has nothing to do with TypeScript. Commented Aug 12, 2016 at 8:56
  • when I use obj1.constructor i ahve this error ""Cannot use 'new' with an expression whose type lacks a call or construct signature."" Commented Aug 12, 2016 at 9:10
  • 1
    Could you please add more information? It is not clear what you really want. Do you want to inherit/extend from another class? Commented Aug 12, 2016 at 9:42

1 Answer 1

2

The typescript compiler will complain if you try to do:

new obj1.constructor()

But you can tell it that it's ok like this:

class A {}

class B extends A {}

type AConstructor = {
    new(): A;
}

type BConstructor = {
    new(): B;
}

let a1 = new A();
let a2 = new (a1.constructor as AConstructor)();

let b1 = new B();
let b2 = new (b1.constructor as BConstructor)();

(code in playground)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.