I'm creating an EventEmitter in typescript, and I can't figure out a way to do the following:
Say I have an interface like this:
interface EventEmitterSubscription { dispose(): void }
// here it is
interface EventEmitter<T extends { [key: string]: any }> {
onAnyEvent(callback: (event: { type: ???, payload: ??? }) => void): EventEmitterSubscription
// ...
}
I can't find a way to type the onAnyEvent callback such that, for example, for an eventEmitter like this:
EventEmitter<{ onNumberReceived: number, onCatReceived: { cat: ICat }, onPersonNameReceived: string }>
The onAnyEvent field would have the type
onAnyEvent(callback: (event: { type: 'onNumberReceived', payload: number } | { type: 'onCatReceived', payload: { cat: ICat } } | { type: 'onPersonNameReceived', payload: string }) => void): EventEmitterSubscription
Currently my implementation has the interface look like:
onAnyEvent(callback: (event: { type: keyof T, payload: T[keyof T] }) => void): EventEmitterSubscription
except that currently doesn't work, as for example that would produce the types onAnyEvent(callback: (event: { type: 'onNumberReceived', payload: number } | {
type: 'onNumberReceived', payload: { cat: ICat } } | /* ... */) => void): EventEmitterSubscription
So how can I type the onAnyEvent field?