【发布时间】:2022-01-13 05:43:41
【问题描述】:
我正在使用适当的 JSDoc 更新我的 shorter-js 代码库以生成 TypeScript 定义,但我无法缩小这一范围。
我有on() sn-p,它使用原生Element.addEventListener,到目前为止一切都很好,
问题是当使用TouchEvent 作为实际处理程序的参数时,TypeScript 会抛出 4 行错误,请参见下面的 sn-p。
/**
* @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%}
on(document.body, 'touchdown', touchdownHandler) 调用会引发以下 4 行错误:
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.
事实上,我在使用document.body.addEventListener(...) 调用时得到了完全相同的结果。所以我在index.d.ts 中尝试了various definitions,但没有解决这个问题。
据我所知,我认为我需要在index.d.ts 中定义一些内容,然后在touchdownHandler 的JSDoc 中使用它。
有什么建议吗?
【问题讨论】:
标签: javascript typescript addeventlistener touch-event jsdoc