我有一个实例化器函数,它返回所提供类的一个实例:
declare type ClassType = { new (): any }; // alias "ParameterlessConstructor"
function getInstance(constructor: ClassType): any {
    return new constructor();
}
我怎么可能让这个函数返回一个实例中的 constructor 参数,而不是any,让我可以实现类型安全,为消费者这个功能呢?
嗯,这很容易,我只需要绕过我自己的代码设置的边界。
关键是将 constructor 参数指定为返回泛型 type 的 newable 类型,该类型与函数返回的泛型类型相同:TgetInstance
function getInstance<T>(constructor: { new (): T }): T {
    return new constructor();
}
这将产生正确的结果:
class Foo {
    public fooProp: string;
}
class Bar {
    public barProp: string;
}
var foo: Foo = getInstance(Foo); // OK
var bar: Foo = getInstance(Bar); // Error: Type 'Bar' is not assignable to type 'Foo'
| 归档时间: | 
 | 
| 查看次数: | 607 次 | 
| 最近记录: |