TypeScript:不能将“new”与类型缺少调用或构造签名的表达式一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31224392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:02:11  来源:igfitidea点击:

TypeScript: Cannot use 'new' with an expression whose type lacks a call or construct signature

typescript

提问by alekop

I have a function that instantiates a object with a given constructor, passing along any arguments.

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

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.');
    }
}

It is used like this:

它是这样使用的:

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

var thing = instantiate(Thing);

This works, but the compiler complains about each new ctorinstance, saying Cannot use 'new' with an expression whose type lacks a call or construct signature.. What type should ctorhave?

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

回答by Ryan Cavanaugh

I'd write it this way (with generics as a bonus):

我会这样写(使用泛型作为奖励):

function instantiate<T>(ctor: { new(...args: any[]): T }): T {

回答by John Zabroski

I also got this error when my type was wrapped in a module, and I was calling new on the module rather than the type. This Q&A helped me rule out some things, and then I came to the realization it was something quite silly after a long day of programming.

当我的类型被包装在一个模块中时,我也遇到了这个错误,我在模块上调用了 new 而不是类型。这个问答帮助我排除了一些事情,然后我意识到在经过一整天的编程之后这很愚蠢。