在扩展 EventEmitter 的 TypeScript 类中声明事件 [英] Declaring events in a TypeScript class which extends EventEmitter

查看:162
本文介绍了在扩展 EventEmitter 的 TypeScript 类中声明事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展 EventEmitter 的类,它可以发出事件 hello.如何使用特定的事件名称和侦听器签名声明 on 方法?

I have a class extends EventEmitter that can emit event hello. How can I declare the on method with specific event name and listener signature?

class MyClass extends events.EventEmitter {

  emitHello(name: string): void {
    this.emit('hello', name);
  }

  // compile error on below line
  on(event: 'hello', listener: (name: string) => void): this;
}

推荐答案

最有用的方法是使用declare:

declare interface MyClass {
    on(event: 'hello', listener: (name: string) => void): this;
    on(event: string, listener: Function): this;
}

class MyClass extends events.EventEmitter {
    emitHello(name: string): void {
        this.emit('hello', name);
    }
}

请注意,如果您要导出您的类,接口和类都必须使用 export 关键字声明.

Note that if you are exporting your class, both the interface and class have to be declared with the export keyword.

这篇关于在扩展 EventEmitter 的 TypeScript 类中声明事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆