Here is a snippet of code that I am working with:
interface Ev<K extends keyof WindowEventMap> {
readonly name: K;
readonly once?: boolean;
readonly callback: (ev: WindowEventMap[K]) => void;
}
function createEventListener<K extends keyof WindowEventMap>({ name, once = false, callback }: Ev<K>): Ev<K> {
return { name, once, callback };
}
const clickEvent = createEventListener({
name: "click",
callback: (ev) => console.log(ev),
});
const scrollEvent = createEventListener({
name: "scroll",
callback: (ev) => console.log(ev),
});
const events = [clickEvent, scrollEvent];
for (const event of events) {
document.addEventListener(event.name, (ev) => event.callback(ev), { once: event.once });
}
In the end of this script, I have a loop set up to access the callback
function of each event. However, there seems to be an issue where I cannot pass the correct parameters because TypeScript has compiled them incorrectly.
This is what TypeScript is currently doing:
(property) Ev<K extends keyof WindowEventMap>.callback: (ev: MouseEvent) => void
What I actually need is:
(property) Ev<K extends keyof WindowEventMap>.callback: (ev: MouseEvent | Event) => void