How to type React events with TypeScript
Sometimes when you write React and TypeScript code, you have to define event handlers. How do you choose the correct event type for them?
Let's say we have an onChange event handler called handleTextChange:
function App() {
const [text, setText] = useState("")
const handleTextChange = (event) => { // 👈 what's the event type?
setText(event.target.value)
}
return (
<form>
<input onChange={handleTextChange} value={text}/>
<button>Submit</button>
</form>
);
}
export default App;
How do you know what is the event type?
The easiest way is to rely on TypeScript type inference. For example, here, instead of passing handleTextChange to onChange, we could try to define an inline function and see what would be the inferred type for the event argument.
This function does not have to have the body defined. We just want to see how would TypeScript type this event object event.
<input onChange={(event) => {}} /> // 👈 check the `event` type
We'll get React.ChangeEvent<HTMLInputElement>, this sounds about right. Now we can use this type for the handleTextChange event.
import { ChangeEvent } from "react"
function App() {
const [text, setText] = useState("")
const handleTextChange = (event: ChangeEvent<HTMLInputElement>) => {
setText(event.target.value)
}
return (
<form>
<input onChange={handleTextChange} value={text}/>
<button>Submit</button>
</form>
);
}
export default App;
Now the event object is typed correctly.
Another option would be to go to react index.d.ts file, that contains the React type definitions.
We can open this file either by pressing CMD + click on our change event or opening node_modules/@types/react/index.d.ts. In this file you can find the list of all the event types defined for react. All the event types accept a type property for the event target element. The types for them can also be found in this file.
And finally you can refer to React documentation for the complete list of supported events.

