我想洗掉事件偵聽器并將其添加到可以聚焦的 HTML 元素(在本例中為按鈕),但我在添加和洗掉事件偵聽器的代碼行上看到了打字稿錯誤:
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.
uj5u.com熱心網友回復:
這個錯誤背后的原因是現有的定義EventListeners在某種意義上非常廣泛和通用,提供的多載沒有為所有可能的事件型別定義它,例如Mouse,Keyboard等。
但是我們可以根據我們的要求為此創建自己的多載,因此對于這個用例,這將解決它!
現在我們已經創建了另外兩個多載來處理我們的特殊情況。
let focusableElements: Element[] = [];
interface Element {
removeEventListener(type: 'keyup' | 'keydown', listener: (event: KeyboardEvent) => any, options?: boolean | EventListenerOptions): void;
addEventListener(type: 'keyup' | 'keydown', listener: (event: KeyboardEvent) => any, options?: boolean | EventListenerOptions): void;
}
focusableElements.forEach((el) => {
el.removeEventListener('keydown', focus_);
el.addEventListener('keydown', focus_);
});
const focus_ = (evt: KeyboardEvent) => {
evt.key // works fine
evt.shiftKey //perfectly fine
}
代碼游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/466119.html
