Using React with Typescript — crash course

the article is also available in my blog: https://www.hoseinh.com/using-react-with-typescript-crash-course/

since it’s relese in 2012, typescript has become more and more popular among developers and most companies and teams use typescript since it’s statically typed and teams can work together with less problems by catching errors and preventing bugs before building or deploying the project.

It is possible to use typescript with react thanks to react-scripts, and create react app also supports typescript and it enables you to setup typescript with react quickly.

In this article you will learn the basics of using ts with react.

Project Setup

setup your react typescript project with the following command:

you will notice that the project files are different, create-react-app creates a tsconfig file for you which you can edit to config ts based on your need and the component files are tsx files which are ts files that support jsx.

so let’s see how can we take advantage of typescript in our react apps:

Functional Components and Props

while we are creating components we have to specify their types, the correct type for functional components is React.FC.

while without typescript we had to use PropTypes library to type component props, we can use ts interfaces to type props and pass the interface to the component type like this:

since the name prop is required, if you forget to pass the prop, ts will show you an error in the ide:

Ts will prevent any potential bugs if you forget required props or pass props with wrong types, without typescript you wouldn’t find out the problem before running the app.

States

Most times you don’t need to specify state types as ts finds out the state types implicitly, for example the count state here is implicitly types as number:

But in some cases we have to explicitly define state types, for example the customer is null by default and it has a Customer type:

Event

when handling events, we have to specify event type to avoid errors:

Conclusion

As we learned in this article, using typescript with react isn’t difficult at all it might feel boring to type everything at first but this more effort pays off in the long term.

front end developer - web designer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store