Borislav Hadzhiev
Sun Apr 17 2022·2 min read
Photo by Jeremy Bishop
Use the React.KeyboardEvent<HTMLElement>
type to type the onKeyDown event in
React. The KeyboardEvent
interface is used for onKeyDown
events. You can
access the value of the key pressed by the user as event.key
.
import React from 'react'; const App = () => { // 👇️ type event as React.KeyboardEvent<HTMLElement> const handleKeyDown = (event: React.KeyboardEvent<HTMLElement>) => { console.log(event.key); }; return ( <div> <input type="text" id="message" name="message" defaultValue="" onKeyDown={handleKeyDown} /> </div> ); }; export default App;
We typed the event as React.KeyboardEvent<HTMLElement>
because the
KeyboardEvent type is
used for onKeyDown
events in React.
However, we could have been more specific when typing the event.
event
parameter in the function.const App = () => { // 👇️ onKeyDown event is written inline // hover over the `event` parameter with your mouse return ( <div> <input type="text" id="message" name="message" defaultValue="" onKeyDown={event => console.log(event)} /> </div> ); }; export default App;
event
parameter and it shows me what the type of the event is.TypeScript is able to infer the type of the event when it's written inline.
This is very useful because it works with all events. Simply write a "mock"
implementation of your event handler inline and hover over the event
parameter
to get its type.
Now that we know that the correct type for the onKeyDown
event in the example
is React.KeyboardEvent<HTMLInputElement>
, we can extract our handler function.
import React from 'react'; const App = () => { // 👇️ type event correctly const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => { console.log(event.key); }; return ( <div> <input type="text" id="message" name="message" defaultValue="" onKeyDown={handleKeyDown} /> </div> ); }; export default App;
The key
property on the KeyboardEvent
object returns the value of the key that was
pressed by the user.
The type we passed to the KeyboardEvent
generic is HTMLInputElement
because
we attached the onKeyDown
event to an input element, however you could be
attaching the event to a different element.
HTML***Element
. Once you start typing HTML..
, your IDE should be able to help you with autocomplete.Some commonly used types are: HTMLInputElement
, HTMLButtonElement
,
HTMLAnchorElement
, HTMLImageElement
, HTMLTextAreaElement
,
HTMLSelectElement
, etc.
onKeyDown
events.As long as you write the event handler function inline and hover over the
event
parameter, TypeScript will be able to infer the event's type.