如何避免 TypeScript 混入的 "unresolved function" 错误?

How to avoid "unresolved function" error with TypeScript mixins?

当我在 TypeScript 上使用 Durandal 的 Events.includeIn() mixin 方法时,WebStorm 报告一个未解析的函数 class:

class Foo {
  bar() {
    ...
    this.trigger('myEvent', payload);  // trigger is unresolved function
    ...
  }
}

Events.includeIn(Foo);

有没有办法在不使用 WebStorm 抑制每个未解决的调用的情况下解决这个问题?

为了在 Foo class 上调用 trigger 方法,您需要将 trigger 方法告知 TypeScript 编译器。您可以通过在 class 定义中的 includeIn 调用之后声明 存在的方法来做到这一点:

class Foo {

  // I'm not sure of the exact parameter/return types
  trigger: (eventName: string, payload: any) => void;

  bar() {
    ...
    this.trigger('myEvent', payload);  // now this function exists
    ...
  }
}

Events.includeIn(Foo);