Home > Software engineering >  React eventListener Type Issue
React eventListener Type Issue

Time:12-09

enter image description here

  useEffect(() => {
    const handleEscClose = (e: KeyboardEvent) => {
      if (e.key === 'Escape') changeVisibility();
    };

    if (isVisible) document.addEventListener('keydown', handleEscClose);
    return () => document.removeEventListener('keydown', handleEscClose);
  }, [changeVisibility, isVisible]);

This code detects esc when the modal is opened. There is a type problem with handleEscClose , so what type should I add?

The following is an error message:

TS2769: No overload matches this call. Overload 1 of 2, '(type: "keydown", listener: (this: Document, ev: KeyboardEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error. Argument of type '(e: KeyboardEvent) => void' is not assignable to parameter of type '(this: Document, ev: KeyboardEvent) => any'. Types of parameters 'e' and 'ev' are incompatible. Type 'KeyboardEvent' is not assignable to type 'KeyboardEvent'. Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error. Argument of type '(e: KeyboardEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.

CodePudding user response:

Don't use KeyboardEvent type import from react. Instead, you should use the DOM event(comes from lib.dom.d.ts). The event is DOM event not React synthetic event

import React from 'react';
// import type { KeyboardEvent } from 'react';

const TestComp = () => {
    const handleEscClose = (e: KeyboardEvent) => {

    }
    React.useEffect(() => {
        document.addEventListener('keydown', handleEscClose)
    }, [])
}

TS playground

  • Related