Using TypeScript in React is awesome but it can be difficult to know *where* and *how* to apply types when you're just getting started.

Here are a few spots to look out for as you're migrating to TypeScript in your React apps 👇
If you're using React function components, you probably want to type-hint your components with React.FC.

Under the hood, this will use the FunctionComponent interface from React's typings.

https://gist.github.com/chenkie/eb1609956f31adf023044d0703d85ca7
React.FC is going to expect an argument which is a type or interface for the props of that component.

For example, if we had a Dashboard component, we might want to pass a DashboardProps type as the argument to React.FC.

https://gist.github.com/chenkie/d3ce07332b6fe24902f47a9b92401e89#file-react-types-ts-L3-L12
If you don't want to use React.FC but you still want type hinting for your props, you can just type-hint the props param with your type or interface.

https://gist.github.com/chenkie/d3ce07332b6fe24902f47a9b92401e89#file-react-types-ts-L14-L33
React ships a lot of types that can be used for event handlers. These are great for giving you type hints on specific events so that your handler functions are easier to write.

Here's an example of the React.DragEventHandler type.

https://gist.github.com/chenkie/d3ce07332b6fe24902f47a9b92401e89#file-react-types-ts-L35-L46
It's quite useful to pass a type argument to useState and other hooks.

While not required, passing the type informs you about what you can do when you update state.

In this example, the state update needs to have an object with a username key.

https://gist.github.com/chenkie/d3ce07332b6fe24902f47a9b92401e89#file-react-types-ts-L48-L75
What about types for props.children?

This one is debated a little bit. I've seen a few different types used:

React.ReactNode
React.ReactChild
React.ReactElement

Note that ReactElement requires that you use an actual element as the child.

https://gist.github.com/chenkie/d3ce07332b6fe24902f47a9b92401e89#file-react-types-ts-L77-L87
There are plenty more but that's a good start. If you have any others, feel free to add them here!
You can follow @ryanchenkie.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.