How to Handle Keyboard Input Events in React TypeScript Application

When dealing with user interactions, you often need to handle some user events like mouse clicks, keyboard input, etc.

Basic Handling#

Unlike with mouse events, TypeScript doesn't provide type declarations for an InputEvent. However, you can use KeyboardEvent for tracking keypresses:

...ChangeEvent for tracking input changes:

...and a basic SyntheticEvent for onInput event:

More Restrictive Handling#

As with the MouseEvent, you can pass a type parameter to either of those events:

Union as a Type Parameter#

To create a general handler for input elements and textarea elements you can use unions as a type parameter:

Extending Events#

If you need to create your own event with additional fields you can extend it from KeyboardEvent, ChangeEvent: