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 .
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)();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.