1

The following code:

  <input
    type="text"
    onKeyPress={(e) => addTag(e)}
  />

  const addTag = (e: React.SyntheticEvent<HTMLInputElement>): void => {
    if (e.key === 'Enter')) {
      // Do something with `e.currentTarget.value`
    }
  };

It results in this error:

Property 'key' does not exist on type 'SyntheticEvent<HTMLInputElement, Event>'.

How shall I type event here? Whatever I use must also work with e.currentTarget.value.

  • See [here](https://stackoverflow.com/questions/40676343/typescript-input-onchange-event-target-value) – Mickers Nov 13 '19 at 15:01
  • @Dupocas actually React normalizes keycodes into strings as of a recent version so `key` is a valid property nowadays. –  Nov 13 '19 at 15:59
  • Yes, that completely escaped my mind. You're right. Deleting the comment then – Dupocas Nov 13 '19 at 16:04

1 Answers1

1

onKeyPress event of React input has this type: (event: React.KeyboardEvent<HTMLInputElement>) => void

Type definition: https://github.com/facebook/react/blob/4cb399a433771c84e861d5ca3d38a24733d23ad8/packages/react-interactions/events/src/dom/Keyboard.js#L36

Honza
  • 683
  • 7
  • 22