只能使用“new”关键字调用void函数

时间:2016-06-13 12:09:27

标签: javascript typescript zurb-foundation

我正试图以下列方式在我的Typescript代码中使用Foundation的Reveal插件(为了便于阅读而改变):

var popup = new Foundation.Reveal($('#element'));

我在编译期间遇到以下错误(最后它确实编译并正常工作):

TS2350: Only a void function can be called with the 'new' keyword.

我应该怎么写呢?

Typescript Playground - code illustrating the problem

3 个答案:

答案 0 :(得分:3)

基于界面:

interface FoundationSitesStatic {
    Reveal(element:Object, options?:IRevealOptions): Reveal;
}

您无法使用new运算符(用于调用构造函数)调用它。

所以修复:

var popup = Foundation.Reveal($('#element'));

答案 1 :(得分:2)

我找到了一种关闭打字稿编译器的方法,但这会放弃类型检查(请谨慎行事)。

var popup = new (Foundation.Reveal as any)($('#element'));

更多示例:

function User2(name) {
    if (this instanceof User2) {
        this.name = name;
    }
    else {
        return new (User2 as any)(name);
    }
}

答案 2 :(得分:0)

我想你想要这个:

interface FoundationSitesStatic {
    Reveal: new (element: Object, options?: IRevealOptions) => Reveal;
}

这可以让您做到无TypeScript错误且不牺牲类型安全性的工作!

const popup = new Foundation.Reveal($('#element'));