Looking to improve my shorter-js
codebase with JSDoc for TypeScript definitions, but hitting a roadblock.
I've implemented the on()
function using Element.addEventListener
, working well so far. However, when passing a TouchEvent
as a parameter for an event handler, TypeScript throws a 4-line error as shown below:
/**
* @param {HTMLElement | Element | Document} element event.target
* @param {string} eventName event.type
* @param {EventListener} handler callback
* @param {EventListenerOptions | boolean | undefined} options other event options
*/
function on(element, eventName, handler, options) {
const ops = options || false;
element.addEventListener(eventName, handler, ops);
}
/**
* test handler
* @type {EventListener}
* @param {TouchEvent} e
*/
function touchdownHandler(e){
console.log(e.touches)
}
// test invocation
on(document.body, 'touchdown', touchdownHandler);
body {height: 100%}
The error is triggered by the
on(document.body, 'touchdown', touchdownHandler)
call and reads as follows:
Argument of type '(e: TouchEvent) => void' is not assignable to parameter of type 'EventListener'.
Type '(e: TouchEvent) => void' is not assignable to type 'EventListener'.
Types of parameters 'e' and 'evt' are incompatible.
Type 'Event' is missing the following properties from type 'TouchEvent': altKey, changedTouches, ctrlKey, metaKey, and 7 more.
Even using
document.body.addEventListener(...)
leads to the same error. I have attempted different definitions in my index.d.ts
file without success.
It seems like I need to define something in my index.d.ts
file and then reference it in the JSDoc for the touchdownHandler
. Any ideas?