When you migrate your React applications from Javascript to Typescript you want everything to be typed right! and If you start having the type any it means that you are in the wrong direction 😞
Ok cool, you have to create your own types, interfaces... but what about React types, for instance React Events types.
For instance you have a submit event
const handleSubmit = (event) => {
event.preventDefault()
const data = new FormData(event.currentTarget)
console.log({
email: data.get('email'),
password: data.get('password'),
})
}
Typescript is complaining and you need to provide a type for your event
You need to know what type is your event here, but how? 🤔
All what you have to do is to write an inline event handler and hover over the event parameter to know that it's of type React.FormEvent<HTMLFormElement>
👍
Great! Here is your new code and Typescript is happy
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
...
Till now everything is good but can't you see that it's a long ugly type 😫 You can make it shorter and nicer.
Let us create a new types file types.ts where we can create new types or in our case only renaming existing ugly ones. Examples bellow
type FormEvent = React.FormEvent<HTMLFormElement>
type MouseEvent = React.MouseEvent<HTMLButtonElement>
type ChangeEvent = React.ChangeEvent<HTMLInputElement>
...
export { FormEvent, MouseEvent, ChangeEvent };
Now our React.FormEvent<HTMLFormElement>
type became FormEvent 😎
Again here is how our code will look like now
import { FormEvent } from './types'
const handleSubmit = (event: FormEvent) => {
...
Short, Clean and Correct.
Thanks for reading and hope it was helpful