【问题标题】:How to tell typescript about functions "mixed in" from another module?如何告诉打字稿有关从另一个模块“混合”的功能?
【发布时间】:2020-09-25 23:11:36
【问题描述】:

我有这种情况:

// 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 实例上不存在......但它确实存在,我如何告诉 typescript 接受这个?

添加这个不起作用:

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

【问题讨论】:

    标签: typescript class mixins


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 2015-05-09
      • 1970-01-01
      • 2018-06-18
      • 2019-11-10
      • 2021-11-04
      • 1970-01-01
      • 2018-07-21
      • 2013-02-25
      • 2017-10-26
      相关资源
      最近更新 更多