Skip to content

Instantly share code, notes, and snippets.

@DrSensor
Forked from rsms/EventListener.d.ts
Created December 22, 2018 17:55
Show Gist options
  • Save DrSensor/e5dcf55ca950c8597da70e509a8fbe05 to your computer and use it in GitHub Desktop.
Save DrSensor/e5dcf55ca950c8597da70e509a8fbe05 to your computer and use it in GitHub Desktop.
Better EventEmitter TypeScript interface
export class EventEmitter<Events, K = keyof Events|symbol> {
addListener(event: K, listener: (...args: any[]) => void): this;
on(event: K, listener: (...args: any[]) => void): this;
once(event: K, listener: (...args: any[]) => void): this;
removeListener(event: K, listener: (...args: any[]) => void): this;
removeAllListeners(event?: K): this;
setMaxListeners(n: number): this;
getMaxListeners(): number;
listeners(event: K): Function[];
emit(event: K, ...args: any[]): boolean;
listenerCount(type: K): number;
// Added in Node 6...
prependListener(event: K, listener: (...args: any[]) => void): this;
prependOnceListener(event: K, listener: (...args: any[]) => void): this;
eventNames(): (K)[];
}
interface PingEvent extends Event {
msg :string
}
interface FooEvents {
"change": Event,
"ping": PingEvent
}
class Foo extends EventEmitter<FooEvents> {
triggerPing(msg :string) {
this.emit("ping", msg)
}
}
const foo = new Foo()
foo.on("ping", msg => console.log('ping event with message', msg))
foo.triggerPing('hello')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment