如何根据TypeScript
中另一个对象的类型创建对象 obj1 = new Object();
obj2 = new "obj1.constructor.name"
我必须这样做,因为Object 1
可以有不同的类。
答案 0 :(得分:2)
如果你尝试这样做,打字稿编译器会抱怨:
new obj1.constructor()
但你可以告诉它,这样就可以了:
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)();