to extend @SergeyK's answer, with this you can get type-checking and completion on both emit
and on
functions without repeating event types.
- Define event listener signatures for each event type:
interface MyClassEvents {
'add': (el: string, wasNew: boolean) => void;
'delete': (changedCount: number) => void;
}
- Declare interface which constructs types for
MyClass
, based on EventListeners (MyClassEvents
) function signature:
declare interface MyClass {
on<U extends keyof MyClassEvents>(
event: U, listener: MyClassEvents[U]
): this;
emit<U extends keyof MyClassEvents>(
event: U, ...args: Parameters<MyClassEvents[U]>
): boolean;
}
- Simply define you class extending
EventEmitter
:
class MyClass extends EventEmitter {
constructor() {
super();
}
}
Now you will get type checking for on
and emit
functions:
Unfortunately you will get completion and type-checking only on those two functions (unless you define more functions inside MyClass interface).
To get more generic solution, you can use this package I wrote.
note: it adds no runtime overhead.
import { TypedEmitter } from 'tiny-typed-emitter';
interface MyClassEvents {
'add': (el: string, wasNew: boolean) => void;
'delete': (changedCount: number) => void;
}
class MyClass extends TypedEmitter<MyClassEvents> {
constructor() {
super();
}
}
on
method is lacking a body.on
method is lacking a body, or you want to declare theevent
parameter as an other type than'hello'
.