Skip to content

Instantly share code, notes, and snippets.

@r4j4h
Forked from rsms/EventListener.d.ts
Created May 9, 2019 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r4j4h/970eb4f428da9d4b01ab110b55acb6b4 to your computer and use it in GitHub Desktop.
Save r4j4h/970eb4f428da9d4b01ab110b55acb6b4 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