Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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