如何告诉打字稿有关另一个模块“混入”的功能?

问题描述

我有这种情况:

// Application.ts
import MicroEvent from 'microevent-github'

class Application {
  // stuff...
  something() {
    // It is also saying "trigger" is undefined,// but it IS defined,MicroEvent defined it.
    this.trigger('foo')
  }
}

// get the `bind`,`unbind`,and other methods from MicroEvent
MicroEvent.mixin(Application)

const app = new Application()

const handleFoo = () => console.log('foo')

// try to use them,get the squiggly errors saying
// `bind` doesn't exist on Application,etc.
application.bind('foo',handleFoo)
application.unbind('foo',handleFoo)

我已经将MicroEvent“混入”到我的应用程序中,这向对象添加了一些方法。但是,VSCode抱怨bindunbind在Application实例上不存在...但是确实存在,我如何告诉打字稿接受这一点?

添加此项无效:

type Application = {
  bind: (eventType: string,callback: () => void) => void
  unbind: (eventType: string,callback: () => void) => void
  trigger: (eventType: string) => void
}

解决方法

Typescript不知道mixin正在修改类。

您可以使用declare语句填充该语句,该语句告诉Typescript存在某些类型,但不提供任何实现。这有点危险,因为您正在创建一个接口,在该接口中没有类型检查可以安全地实现,但是在使用无类型库时,您可能别无选择。

class Application {
    declare bind: (eventType: string,callback: () => void) => void
    declare unbind: (eventType: string,callback: () => void) => void
    declare trigger: (eventType: string) => void

    //...
}

Playground


要重用此方法,您可以创建一个声明这些方法的抽象基类,并从其继承。

abstract class MicroEventBase {
  declare bind: (eventType: string,callback: () => void) => void
  declare unbind: (eventType: string,callback: () => void) => void
  declare trigger: (eventType: string) => void
}

class Application extends MicroEventBase {
  //...
}

Playground