Typescript/React what's the correct type of the parameter for onKeyPress? Typescript/React what's the correct type of the parameter for onKeyPress? typescript typescript

Typescript/React what's the correct type of the parameter for onKeyPress?


This seems to work:

handleKeywordKeyPress = (e: React.KeyboardEvent<FormControl>) =>{  if( e.key == 'Enter' ){    if( this.isFormValid() ){      this.handleCreateClicked();    }  }};

The key(Ha ha) here, for me, was to specify React.KeyboardEvent, rather than KeyboardEvent.

Trolling around the React code, I was seeing definitions like:

type KeyboardEventHandler<T> = EventHandler<KeyboardEvent<T>>;

But didn't realise that when I was copy/pasting KeyboardEvent as the parameter type for my handler, the compiler was actually picking up the KeyboardEvent which is some kind of default type defined in the Typescript libraries somewhere (rather than the React definition).


The type of onKeyPress should be KeyboardEventHandler<T>, which can be written in either of the following ways:

handleKeywordKeypress: KeyboardEventHandler<FormControl> = e => {    // use e.keyCode in here}

or

import { KeyboardEvent } from "react";handleKeywordKeypress = (e: KeyboardEvent<FormControl>) => {    // use e.keyCode in here};

As you identified in your answer, if you go with the second option, you need to specifically use KeyboardEvent from React.

Note that the keyCode is directly available as a property on e; you don't need to access it via the nativeEvent.

Also, the generic type parameter T should be the FormControl component, rather than its props, so you should change your other handler too.