I'm attempting to make an emit function that can accept multiple arguments. Furthermore, the 2nd argument and beyond will be validated by TypeScript based on the 1st argument (the event).
I have the code below as a starting point, but it obviously doesn't work 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 valid
emit('error', new Error('Ouch'), { count: 5 });
// This should be invalid
emit('error', 123, 456);
on()entirely? Seems irrelevant to the question