I'm updating my shorter-js
codebase with proper JSDoc to generate TypeScript definitions but I'm unable to narrow down this one.
I have the on()
snippet which makes use of native Element.addEventListener
, so far so good,
the problem is when using TouchEvent
as a parameter for an actual handler, TypeScript throws a 4 line error, see below snippet.
/**
* @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 on(document.body, 'touchdown', touchdownHandler)
invocation throws this 4 line error:
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.
In fact I get the exact same when using document.body.addEventListener(...)
invocation. So I've tried various definitions within my index.d.ts
, but nothing to resolve this.
To my knowledge I think I need to define something in my index.d.ts
, then use it in the JSDoc for the touchdownHandler
.
Any suggestions?