【问题标题】:Only void function can be called with the "new" keyword只能使用“new”关键字调用 void 函数
【发布时间】:2016-06-13 12:09:26
【问题描述】:

我正在尝试通过以下方式在我的 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

【问题讨论】:

  • 我认为你把事情搞砸了。如果 Reveal 是一个返回对象的函数,你为什么要做一个 new 呢?
  • 到目前为止,这是我让它工作的唯一方法......
  • 根据 Playground 中的代码,您应该这样做:var popup = Foundation.Reveal($('#element'))(即没有new

标签: javascript typescript zurb-foundation


【解决方案1】:

我找到了关闭 typescript 编译器的方法,但这会放弃类型检查(请谨慎操作)。

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】:

    基于界面:

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

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

    所以修复:

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

    【讨论】:

    • 是的,它可以编译,但它不起作用:)这就是我问这个问题的原因;)
    • 我认为它是有效的 JavaScript,但在 TypeScript 中无效。这也让我感到困惑,就像@Wiktor,因为他们说 TypeScript 是 JavaScript 的超集。但现在看来,实际上并没有。
    • 是的,这个问题是......当我使用 new 运算符调用它时,我的代码是正确的,而当我不调用它时,它有一个错误。所以我真的只需要一种方法来关闭打字稿编译器
    【解决方案3】:

    我想你想要这个:

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

    这让您可以在没有 TypeScript 错误且不牺牲类型安全的情况下完成工作!

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

    【讨论】:

      猜你喜欢
      • 2017-09-15
      • 2019-07-21
      • 1970-01-01
      • 2020-02-26
      • 2015-08-21
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多