TypeScript:不能对类型缺少调用或构造签名的表达式使用"new"

ale*_*kop 14 typescript

我有一个函数,用给定的构造函数实例化一个对象,传递任何参数.

function instantiate(ctor:Function):any {
    switch (arguments.length) {
        case 1:
            return new ctor();
        case 2:
            return new ctor(arguments[1]);
        case 3:
            return new ctor(arguments[1], arguments[2]);
        ...
        default:
            throw new Error('"instantiate" called with too many arguments.');
    }
}
Run Code Online (Sandbox Code Playgroud)

它是这样使用的:

export class Thing {
    constructor() { ... }
}

var thing = instantiate(Thing);
Run Code Online (Sandbox Code Playgroud)

这有效,但编译器抱怨每个new ctor实例,说Cannot use 'new' with an expression whose type lacks a call or construct signature..应该ctor有什么类型?

Rya*_*ugh 19

我这样写(以泛型作为奖励):

function instantiate<T>(ctor: { new(...args: any[]): T }): T {
Run Code Online (Sandbox Code Playgroud)

  • 我也是.你能否提供一些人可以找到一些文档的提示. (2认同)