skip to Main Content

I have a function:

    const handleHotKeys = (event: KeyboardEvent): void => {
      // other code here
    };

and markup like this:

return (
      <label
        htmlFor={id}
        className='flex flex-col items-start gap-1 w-full md:w-2/4 text-lg relative'
      >
            <textarea
              placeholder={placeholder}
              id={id}
              className='customScroll w-full'
              value={value}
              onChange={(e) => onChange(e.target.value)}
              onKeyDown={getHotkeyHandler([
                ['mod+B', handleHotKeys],
                ['mod+I', handleHotKeys],
                ['mod+alt+T', handleHotKeys],
                ['mod+alt+C', handleHotKeys],
                ['shift+(', handleHotKeys],
                ['[', handleHotKeys],
                ['shift+{', handleHotKeys]
              ])}
            />
      </label>
    );

The following error appears: Type ‘(event: KeyboardEvent) => void‘ is not assignable to type ‘(event: KeyboardEvent | React.KeyboardEvent<HTMLElement>) => void‘. Types of parameters ‘event‘ and ‘event‘ are incompatible. Type ‘KeyboardEvent | React.KeyboardEvent<HTMLElement>‘ is not assignable to type ‘KeyboardEvent<Element>‘. Type ‘KeyboardEvent‘ is missing the following properties from type ‘KeyboardEvent<Element>‘: locale, nativeEvent, isDefaultPrevented, isPropagationStopped, persist ts(2322).

Typescript 5.2.2
getHotkeyHandler is a function from mantine hooks library (checked the docs, didn’t help)
KeyboardEvent from React is imported

I tried a lot of things (googled it, asked chatgpt), but nothing works for me, error still appears.
I tried React.KeyboardEvent<HTMLTextAreaElement> and KeyboardEvent | React.KeyboardEvent<HTMLElement> this don’t work too.

I will be very grateful if you can tell me how to fix it.

2

Answers


  1. Chosen as BEST ANSWER

    getHotkeyHandler function expect a more general KeyboardEvent type.

    For me helped this type: React.KeyboardEvent<HTMLElement> | KeyboardEvent

    React.KeyboardEvent<HTMLElement> is KeyboardEvent from React, exactly <HTMLElement>, even i have textarea if i type it like React.KeyboardEvent<HTMLTextAreaElement> it doesn't work.

    And KeyboardEvent the default type from Typescript.

    Only this worked for me.


  2. Make sure you import KeyboardEvent from react, there is a native type with the same name.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search