I
I
Ilya Korotkov2021-10-10 15:56:24
typescript
Ilya Korotkov, 2021-10-10 15:56:24

How to properly handle events in React + Typescript?

Good day to all!
I am working on the function of closing modals by ESC in a React + Typescript project. I encountered
the following problem: when hanging an event handler on an element, TS does not accept the React.KeyBoardEvent type specified as the type of the event parameter in the corresponding function:

const closeByESC = (event: React.KeyboardEvent) => {
    if (event.key === "Escape") {
      return closePopup();
    }
  }
...
    document.addEventListener('keydown', (event) => {
      return closeByESC(event); - ошибка. "Аргумент типа "KeyboardEvent" нельзя назначить параметру типа 
               "KeyboardEvent<Element>". В типе "KeyboardEvent" отсутствуют следующие свойства из типа 
               "KeyboardEvent<Element>": locale, nativeEvent, isDefaultPrevented, isPropagationStopped, persist"
    })

The description of the error speaks for itself, there are some properties in the React synthetic event that are apparently not in the standard 'keydown'. If you specify KeyboardEvent as the parameter type, everything works. It became interesting what are the ways to solve this problem. If you can share code examples, doubly grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-10-10
@Aetae

Well, yes.
React.KeyboardEventis a synthetic event that is generated in React.
KeyboardEventis the original event that is generated in the browser.
KeyboardEventlies in event.nativeEventu React.KeyboardEvent.
If you basically don’t care where the event will arrive in the function, and you are only interested in common properties, do this:

const closeByESC = (event: KeyboardEvent | React.KeyboardEvent) => {

PS Well, you don't need extra wrappers:document.addEventListener('keydown', closeByESC);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question