将类作为参数并返回该类的实例的函数的类型

Joh*_*isz 5 typescript

我有一个实例化器函数,它返回所提供类的一个实例:

declare type ClassType = { new (): any }; // alias "ParameterlessConstructor"

function getInstance(constructor: ClassType): any {
    return new constructor();
}
Run Code Online (Sandbox Code Playgroud)

我怎么可能让这个函数返回一个实例中的 constructor 参数,而不是any,让我可以实现类型安全,为消费者这个功能呢?

Joh*_*isz 5

嗯,这很容易,我只需要绕过我自己的代码设置的边界。


关键是将 constructor 参数指定为返回泛型 type 的 newable 类型,该类型与函数返回的泛型类型相同TgetInstance

function getInstance<T>(constructor: { new (): T }): T {
    return new constructor();
}
Run Code Online (Sandbox Code Playgroud)

这将产生正确的结果:

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'
Run Code Online (Sandbox Code Playgroud)