【问题标题】:Typed events on class in TypeScript [duplicate]TypeScript中类的类型事件[重复]
【发布时间】:2020-09-01 11:11:39
【问题描述】:

我在 typescript 中有一个类,我想在其中发出一个事件。 现在我知道我的代码需要什么才能正常工作。但我想要这个,因为它很好。

我的课程扩展了the EventEmitter class,我想发出事件“检查”(这有效)。 我想要的是在 Visual Studio Code 中列出可能的智能感知等事件列表。

我将如何在 TypeScript 中执行此操作?

【问题讨论】:

  • 你的意思是Angular's EventEmitter?它有一个generic type 来指定可以发出什么,您可以使用string literal type 来表示'check' 和其他有效事件。
  • 我根本没有使用 Angular,我说的是 NodeJS EventEmitter
  • 您应该会看到一个接受副本的选项。

标签: node.js typescript


【解决方案1】:

我知道有两种可能的方法:

第一个

很简单,你可以使用像typed-event-emitter这样的npm包。

包本身的代码示例:

import { EventEmitter } from 'typed-event-emitter';

class MyClass extends EventEmitter {
  onValueChanged = this.registerEvent<(newValue: number) => any>();

  private _value: number;

  constructor(value: number) {
    // initialize EventEmitter
    super();

    this._value = value;
  }

  get value() {
    return this._value;
  }

  set value(value: number) {
    this._value = value;
    this.emit(this.onValueChanged, this._value);
  }
}

let instance = new MyClass(0);
instance.onValueChanged(newValue => {
  console.log(`Value changed: ${newValue}`);
});

instance.value = 27;

第二个

如果你不想使用 npm 包并且想自己声明,你可以在你的类上使用declare interface

以下是此类声明的简短示例:

export declare interface Animal {
  on: (event: 'tick', listener: () => void) => this
  emit: (event: 'tick') => boolean
}

export class Animal extends EventEmitter {}

【讨论】:

  • 第二个选项非常适合我,谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 2020-07-08
  • 2018-03-13
  • 2019-08-01
  • 2020-04-09
  • 2021-09-10
  • 2016-11-15
  • 2016-06-28
相关资源
最近更新 更多