How to Migrate a React App to TypeScript
When I first started learning TypeScript, one of the suggestions I often heard was, “convert one of your existing projects! It’s the best way to learn!” Soon after, a friend from Twitter offered to do just that — show me how to migrate a React app to TypeScript.
The purpose of this article is to be that friend for you and help you migrate your own project to TypeScript. For context, I will be using pieces from a personal project which I migrated while going through this process myself.
To make this process feel less daunting, we’ll break this down into steps so that you can execute the migration in individual chunks. I always find this helpful when taking on a large task. Here are all the steps we’ll take to migrate our project:
- Add TypeScript
- Start simple
- Convert all files
- Increase strictness
- Clean it up
NOTE: the most important step in this whole process is number 9. Although we can only get there by working through them in sequential order.
1. Add TypeScript to the Project
First, we need to add TypeScript to our project. Assuming your React project was bootstrapped with
create-react-app, we can follow the docs and run:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
or if you’re using
yarn add typescript @types/node @types/react @types/react-dom @types/jest
Notice we haven’t changed anything to TypeScript yet. If we run the command to start the project locally (
yarn start in my case), nothing should be different. If that’s the case, then great! We’re ready for the next step.
2. Add the
Before we can take advantage of TypeScript, we need to configure this via the
tsconfig.json. The simplest way for us to get started is to scaffold one using this command:
npx tsc --init
This gets us some basics.
We have not yet interacted with TypeScript. We have only taken the necessary actions to get things ready. Our next step is to migrate a file to TypeScript. With this, we can complete this step and move onto the next.
3. Start with a Simple Component
The beauty of TypeScript is that you can incrementally adopt it. We can start with a simple component for our first piece of this migration. For my project, I’m going to start with an SVG component that looks like this:
The post How to Migrate a React App to TypeScript appeared first on SitePoint.