我有以下实现,如果不考虑typescript的话它可以正常工作。
const escFunction: (event: React.KeyboardEvent<Element>) => any = useCallback((event: React.KeyboardEvent["keydown"]) => {
if (event.keyCode === KEY_CODE.ESC) {
closeFn();
}
}, [closeFn]);
if (closeTimeout) {
setTimeout(closeFn, closeTimeout);
}
useEffect(() => {
if (shouldCloseOnEsc) {
document.addEventListener(KEY_EVENT.KEYDOWN, escFunction, false);
}
return () => {
if (shouldCloseOnEsc) {
document.removeEventListener(KEY_EVENT.KEYDOWN, escFunction, false);
}
}
}, [shouldCloseOnEsc, escFunction]);
但是 document.addEventListener
和 document.addEventListener
显示了typescript错误,如下所示:
TypeScript error in /mnt/d/Projects/sb-modal/src/components/modal/Modal.tsx(63,7):
No overload matches this call.
Overload 1 of 2, '(type: "input" | "progress" | "select" | "cancel" | "keydown" | "fullscreenchange" | "fullscreenerror" | "pointerlockchange" | "pointerlockerror" | "readystatechange" | "visibilitychange" | ... 85 more ... | "paste", listener: (this: Document, ev: MouseEvent | ... 14 more ... | ClipboardEvent) => any, options?: boolean | AddEventListenerOptions): void', gave the following error.
Argument of type 'string' is not assignable to parameter of type '"input" | "progress" | "select" | "cancel" | "keydown" | "fullscreenchange" | "fullscreenerror" | "pointerlockchange" | "pointerlockerror" | "readystatechange" | "visibilitychange" | ... 85 more ... | "paste"'.
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void', gave the following error.
Argument of type '(event: KeyboardEvent<Element>) => any' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type '(event: KeyboardEvent<Element>) => any' is not assignable to type 'EventListener'.
Types of parameters 'event' and 'evt' are incompatible.
Type 'Event' is missing the following properties from type 'KeyboardEvent<Element>': altKey, charCode, ctrlKey, getModifierState, and 12 more. TS2769
61 | useEffect(() => {
62 | if (shouldCloseOnEsc) {
> 63 | document.addEventListener(KEY_EVENT.KEYDOWN, escFunction, false);
| ^
64 | }
65 | return () => {
66 | if (shouldCloseOnEsc) {
现在,如果我将行
const escFunction: (event: React.KeyboardEvent<Element>) => any = useCallback((event: React.KeyboardEvent<Element>) => {
更改为const escFunction: any = useCallback((event: React.KeyboardEvent<Element>) => {
,则编译正常。
我正在使用react-16.8.x create-react-app进行安装。
const escFunction: (event: Event) => any = useCallback((event: KeyboardEvent): void => {
时,我遇到了错误提示Type 'Event' is missing the following properties from type 'KeyboardEvent'
。 - Vinay Prajapati