I have a function that takes an HTMLElement and an object; the object's keys are event types and the values are functions:
function addListeners(el: HTMLElement, listeners: { [key in keyof HTMLElementEventMap]: Function }) {
if (listeners) {
for (const [key, value] of Object.entries(listeners)) {
el.addEventListener(key, value);
}
}
}
However, Typescript raises these two errors:
No overload matches this call.
Overload 1 of 2, '(type: keyof HTMLElementEventMap, listener: (this: HTMLElement, ev: Event | ClipboardEvent | UIEvent | AnimationEvent | MouseEvent | ... 13 more ... | WheelEvent) => any, options?: boolean | ... 1 more ... | undefined): void', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'keyof HTMLElementEventMap'.
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type 'Function' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.