5

I am trying to put my keyup event with TS but using any|KeyboardEvent does not work.

How to type events in React?

TS Error

Type '(e: KeyboardEvent) => void' is not assignable to type 'KeyboardEventHandler<HTMLInputElement>'.
  Types of parameters 'e' and 'event' are incompatible.
    Type 'KeyboardEvent<HTMLInputElement>' is missing the following properties from type 'KeyboardEvent': char, isComposing, DOM_KEY_LOCATION_LEFT, DOM_KEY_LOCATION_NUMPAD, and 15 more.  TS2322

Component

<input
  type="text"
  placeholder="Search for claim ID"
  onKeyUp={(e: KeyboardEvent) => {
    console.info();
  }}
/>
10
  • I'm not particularly well verse in React, but it looks like you're setting onKeyUp, which is a Keyboard Event, to an empty object. Surely instead, onKeyUp="console.info($event)" would work? Commented Jul 5, 2021 at 12:53
  • @cmprogram what empty object? That's an arrow function within JSX interpolation. Commented Jul 5, 2021 at 12:54
  • 1
    Thanks @Apostolos it changes the error to Type 'KeyboardEvent' is not generic. TS2315 Commented Jul 5, 2021 at 12:57
  • 1
    Does this StackOverflow answer help you? I.e, try using the KeyboardEvent component from React: React.KeyboardEvent<HTMLInputElement> Commented Jul 5, 2021 at 12:58
  • 1
    @BaoHuynhLam is correct. the correct way is onKeyUp={(e: React.KeyboardEvent<HTMLInputElement>) => { Commented Jul 5, 2021 at 13:02

2 Answers 2

17

First of all, as Bao Huynh Lam stated in comments, you need to use this

onKeyUp={(e: React.KeyboardEvent<HTMLInputElement>) => {

as type of event. Then, in order to take the value of input, you can cast e.target as HTMLInputElement and then get its value.

Check this small sandbox

<input
  type="text"
  placeholder="Search for claim ID"
  onKeyUp={(e: React.KeyboardEvent<HTMLInputElement>) => {
    console.info((e.target as HTMLInputElement).value);
  }}
/>
Sign up to request clarification or add additional context in comments.

Comments

0

According to this guide of handling keyboard events, it seems that your type check e: keyboardEvent should be e: React.KeyBoardEvent<HTMLInputElement>. Also, see this related answer for onkeypress. Also you may want to set the types in a separate line as shown here.
Bonus: relevant answer here for this topic.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.