onKeyDown Event in React with TypeScript

Viewed 3500

In my React component I have the following input element:

  <input
    max={120}
    type="number"
    value={numValue}
    onKeyDown={handleKeyDown}
  />

And this is my handleKeyDown function:

  const handleKeyDown = (evt: KeyboardEvent) => {
    console.log(evt.key);
    console.log(evt.target.value);
  }

And this is the error I get from TypeScript

Property 'value' does not exist on type 'EventTarget'.

What is the event type I need to assign so that it covers both the evt.target.value and the evt.key ?

2 Answers

There are two issues:

The way you write your code prevents the TypeScript compiler to infer the type of the event's current target. You can either inline the function like this:

  <input max={120} type="number" value={numValue} onKeyDown={(evt) => {...}} />

or help the compiler out like this:

  const handleKeyDown = (evt: React.KeyboardEvent<HTMLInputElement>) => {...}

But the problem won't go away, because, even if in this instance we are sure that evt.target is an instance of HTMLInputElement, we can't be in the general case. For instance, if your event handler was attached to a <div> with an <input> inside, the div could receive events where evt.target is not an HTMLDivElement but an HTMLInputElement because of event bubbling!

evt.currentTarget would achieve what you want. Or, in this particular case, a type assertion ((evt.target as HTMLInputElement).value) is also safe.

You just need to make a little change in your function

const handleKeyDown = (evt) => {
    console.log(evt.key);
    console.log(evt.target.value);
    // set num value here
}
Related