Using TypeScript with React
Intro guide to using TS with React
As i’ve said before said before using typescript with pre-existing projects can be a hassle due to the need of going back through the whole app to declare typing but if you are a React dev like me, here’s a quick guide on using TypeScript with React.
This guide might not be for everyone since this is only for React developers but if you are a React dev and want to learn Typescript, you can check out my previous guide on typescript basics.
React has TypeScript support so you all you need to do is just run your normal create React app command with the TS template flag
npx create-react-app <app-name> --template typescript
Using the TS template flag creates a similar looking React boilerplate app but if you look again your files with .js & .jsx extensions are replaced with .ts & .tsx instead and additionally a json file named tsconfig.json which like the name suggests, contains your configurations for the TS compiler, .
For my example I will be building out a simple counter app. After the React boilerplate is finished installing, I created a a component folder within the src directory and created two components( Count.tsx & Counter.tsx) and replaced the React boilerplate code in the App.tsx with my code.
First Let’s look at the Count component
TS and React are so compatible these days, you can simply declare the typing of Count as a React functional Component that takes in a prop which will be this component’s count prop with the typing of number. This is really important for using TypeScript with React, this is greatly useful in a real world scenario where other developers might work on your code in the future and they randomly try to add in numbers as strings. I find this to be great a developers since this will throw an error before the product ever gets in the hands of the customer.
Next, let’s look at our next example of a react class component now
You can see in the above example that I’ve simple declared the Props interface that can take in any data and the State interface that only has a count with the typing of number.
That’s it! I hope this article gave you enough insight on wether or not to use Typescript with React. I personally would be using TS with React in the future due to its flexibility. It’s great that you can catch simple errors by predefining types to your components or simple choose not to define it’s typing in the case of using props where you want the flexibility of passing any thing as a prop down the node tree.
Explaining TS with React will be too long of an article for one sitting. I will be starting a series of React articles that will teach all the concepts going from beginner to advanced.
If you enjoyed this article, please follow or leave a comment and check out my other articles on Medium.