The idea is to store typed callbacks within a Map
using something like the following example (the types are incorrect, example meant to show intentions)
type Events = { type: 'e1' } | { type: 'e2' };
type AddListener = <const EventName extends Events['type']>(
eventName: EventName,
cb: (event: Extract<Events, { type: EventName }>) => void,
) => () => void;
const addListener: AddListener = (eventName, cb) => {
type ListenersMap = {
[key in Events['type']]?: Set<(event: Extract<Events, { type: key }>) => void>;
};
const listenersMap: ListenersMap = new Map(); // Incorrect types
return function removeEventListener() {
/* ... */
};
};
(playground link)
Is there a way of linking the type of the keys of a map to its values to accomplish something like above?