I am currently working on creating an emit
function that has the capability to accept multiple arguments. In addition, TypeScript will validate the 2nd argument and beyond based on the 1st argument (the event).
The code provided below is a starting point, but it is not functioning as intended.
type CallbackFunc<T extends any[]> = (...args: T) => void;
interface TrackablePlayerEventMap {
'play:other': CallbackFunc<['audio' | 'video']>;
error: CallbackFunc<[Error, Record<string, unknown>]>;
}
const eventHandlers: Partial<TrackablePlayerEventMap> = {};
function on<K extends keyof TrackablePlayerEventMap>(event: K, callback: TrackablePlayerEventMap[K]) {
}
function emit<K extends keyof TrackablePlayerEventMap>(event: K, ...args: TrackablePlayerEventMap[K]) {
const handler = eventHandlers[event];
handler(...args);
}
on('error', (e, metadata) => {
console.log(e, metadata)
});
on('play:other', x => {
console.log(x);
});
// This should be considered valid
emit('error', new Error('Ouch'), { count: 5 });
// This should be deemed invalid
emit('error', 123, 456);