addEvenListener上的打字稿问题

问题描述 投票:0回答:1

我有下面的实现,如果我不用担心打字稿的话,可以很好地工作。

  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.addEventListenerdocument.addEventListener显示打字稿错误,如下所示:

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安装。

javascript reactjs typescript
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.