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

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);
    }
}

注意,如果你是exporting你的类,both接口和类必须用export关键字声明.

Typescript相关问答推荐

Angular 17 -如何在for循环内创建一些加载?

动态判断TypScript对象是否具有不带自定义类型保护的键

是否可以根据嵌套属性来更改接口中属性的类型?

在键和值为ARGS的泛型函数中未正确推断类型

泛型函数即使没有提供类型

使用泛型keyof索引类型以在if-condition内类型推断

类型脚本基于数组作为泛型参数展开类型

TypeScrip:逐个 case Select 退出noUncheck kedIndexedAccess

如何将泛型对象作为返回类型添加到类型脚本中

使用2个泛型类型参数透明地处理函数中的联合类型

分解对象时出现打字错误

按函数名的类型安全类型脚本方法包装帮助器

不带其他属性的精确函数返回类型

@TANSTACK/REACT-QUERY中发生Mutations 后的数据刷新问题

ANGLE订阅要么不更新价值,要么不识别价值变化

我怎样才能正确地输入这个函数,使它在没有提供正确的参数时出错

TypeScrip:使用Union ToInterval辅助对象,但保留子表达式

仅当类型为联合类型时映射属性类型

如何正确键入泛型相对记录值类型?

TS2532:对象可能未定义