我想删除事件侦听器并将其添加到可以聚焦的 HTML 元素(在本例中为按钮),但我在添加和删除事件侦听器的代码行上看到了typescript错误:
focusableElements.forEach((el) => {
el.removeEventListener('keydown', focus);
el.addEventListener('keydown', focus);
});
focus 像这样接受一个 KeyboardEvent
const focus = (evt: KeyboardEvent) => {
.... in here we have code that uses evt.key and evt.shiftKey
}
这是我看到的确切错误
No overload matches this call.
Overload 1 of 2, '(type: keyof ElementEventMap, listener: (this: Element, ev: Event) => any, options?: boolean | EventListenerOptions | undefined): void', gave the following error.
Argument of type '"keydown"' is not assignable to parameter of type 'keyof ElementEventMap'.
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions | undefined): void', gave the following error.
Argument of type '(evt: KeyboardEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type '(evt: KeyboardEvent) => void' is not assignable to type 'EventListener'.
Types of parameters 'evt' and 'evt' are incompatible.
Type 'Event' is missing the following properties from type 'KeyboardEvent': altKey, charCode, code, ctrlKey, and 17 more.
我尝试更改KeyboardEvent为,Event但由于我们使用evt.key和evt.shiftKey.