The only way shown in the handbook to do something similar to this is to send the class you want to initialize as a parameter to the factory method, and describe it's constructor using the new keyword.
function factory<T>(type: { new (): T }): T {
return new type();
}
class SomeClass { }
let result = factory(SomeClass);
The result will be of type SomeClass.
The constructor of the class will be type checked against the interface defined in the factory method.
If you want to initialize a class that takes a parameter in it's constructor you will have to specify that in the interface given to the factory method.
function factory<T>(type: { new (...args): T }, ...args): T {
return new type(...args);
}
class SomeClass {
constructor(name: string) { }
}
let a = factory(SomeClass, 'John Doe');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…