Migrating an existing React project to TypeScript: Step-by-step guide
When you are first learning TypeScript, you often hear suggestions: "Switch an existing project! This is the best way to learn!" Not long after, a friend on Twitter offered to help me do this- —Show me how to migrate a React app to TypeScript.
This article is intended to be your friend and help you migrate your projects to TypeScript. To illustrate, I will use some fragments from my personal project that I migrated myself during the migration process.
Key Points
- Start migrating React applications to TypeScript by adding TypeScript to the project, adding tsconfig.json, starting with simplicity, converting all files, increasing stringency, cleaning and celebrating successful migrations.
- Step by adopting TypeScript, starting with a simple component. Change the file extension to .tsx and add a type comment. Convert all files in the project step by step.
- Improve the strictness of tsconfig.json by enabling stricter rules. This can be done step by step, fixing them when errors occur. The goal is to move forward quickly and return later to fix any issues.
- Use shortcuts like @ts-ignore and FixMeLater to relieve the burden during the migration process. Over time, prioritize replacing these shortcuts with the correct type safety.
Plan
To make this process less daunting, we'll break it down into steps so you can perform the migration in chunks. I always find this helpful when dealing with large tasks. Here are all the steps we will take to migrate our project:
- Add TypeScript
- Add tsconfig.json
- Start with simplicity
- Convert all files
- Improve strictness
- Cleaning
- Celebrate
Note: The most important step in the whole process is step 7. Although we can only complete these steps in order to get there.
1. Add TypeScript to the project
First, we need to add TypeScript to our project. Assuming your React project is booted with create-react-app, we can run it as per the document:
<code>npm install --save typescript @types/node @types/react @types/react-dom @types/jest</code>
Or if you are using yarn:
<code>yarn add typescript @types/node @types/react @types/react-dom @types/jest</code>
Please note that we have not changed anything to TypeScript yet. If we run the command to start the project locally (yarn start in my case), nothing changes. If this is the case, that would be great! We are ready to move to the next step.
2. Add tsconfig.json
Before we can leverage TypeScript, we need to configure it through tsconfig.json. The simple way we start is to build one using the following command:
<code>npx tsc --init</code>
This gives us some basic knowledge.
We have not interacted with TypeScript yet. We just took the necessary measures to prepare. Our next step is to migrate the file to TypeScript. With this we can complete this step and move on to the next step.
3. Start with a simple component
The beauty of TypeScript is that you can adopt it step by step. We can start the first part of the migration from a simple component. For my project, I'll start with a Button component that looks like this:
<code>npm install --save typescript @types/node @types/react @types/react-dom @types/jest</code>
To convert it correctly, we need to do two things:
- Change the file extension to .tsx
- Add a type comment
Since this component uses two props, we need to change something:
<code>yarn add typescript @types/node @types/react @types/react-dom @types/jest</code>
Let's double check that everything is working properly by running the project to make sure we're not breaking anything. Please note that here react-scripts automatically detects new changes and modify tsconfig.json for us! Look! How beautiful is this?
If everything goes well, our project will remain working. Pat your back! You have successfully migrated your first file to TypeScript. If we want to stop here, we can, but let's keep moving forward.
4. Convert all files
The next step is to perform step 3 on all files in the project. If the project you are migrating is quite large, I recommend you do this multiple iterations. Otherwise, you may exhaust yourself.
In this step, you may need to add additional packages according to the third-party library you are using. For example, I'm using moment, so I have to run yarn add -D @types/moment to add the type as devDependency.
When doing this, you need to remember the following points:
- Suppress TypeScript error by adding // @ts-ignore in the line before the error
- If the file uses jsx (i.e.
), the file extension must be .tsx instead of .ts - Run the project locally to make sure everything is working (they should be)
After completing this step, the difficult work is completed! Our project will use TypeScript, but we need to increase our rigor to take advantage of its advantages.
5. Improve the strictness of tsconfig.json
Now we can improve stringency by enabling stricter rules in tsconfig.json. Thankfully, react-scripts notifies us of any type of error when running our project locally. We will follow the steps below:
- Enable rules
- Local startup project
- Fix the error
We will repeat this process for the following rules:
- "noImplicitAny": true
- "strictNullChecks": true
- "noImplicitThis": true
- "alwaysStrict": true
I want to share a trick. If you find something implicitly has type any and you are not sure how to fix it at this point, don't fix it. Create this and use it to eliminate errors:
<code>npx tsc --init</code>
Our goal is to move forward quickly and return to fix these issues later.
This will bring greater type safety to our projects. If you want to read more about compiler options, you can read the relevant content in the TypeScript manual.
After this is done, we can replace these:
- "noImplicitAny": true
- "strictNullChecks": true
- "noImplicitThis": true
- "alwaysStrict": true
Use this:
- "strict": true
This also enables these strict options:
- strictBindCallApply
- strictNullChecks
- strictFunctionTypes
- strictPropertyInitialization
At this point, we have reached the standard strictness level in the project. If we want to add additional checks, we can add these rules:
- "noUnusedLocals": true
- "noUnusedParameters": true
- "noImplicitReturns": true
- "noFallthroughCasesInSwitch": true
Once we reach the level of strictness that we are satisfied with, we can move on to the next step.
6. Clean the shortcut
If you added @ts-ignore or used the FixMeLater type, it's time to go back and fix them. We don't have to do all of this at once, or never, but this will be the last step to ensure maximum type safety in the project.
Sometimes the effort to fix these is not worth the time, but sometimes it is worth it. You have to discuss with your team and decide what makes sense.
7. Celebrate
We did it! We officially moved the project to TypeScript. Take some time to celebrate your work. This is certainly not a trivial matter. Especially if you are working in a large code base.
Things to remember
As we review our work, here are some things to remember when migrating our React project to TypeScript.
Start from small things
Use the ability to gradually adopt TypeScript. Do it one document at a time, at your own pace. Do what makes sense to you and your team. Don't try to solve all problems at once.
Advance strictness over time
No need to be of maximum rigor from the beginning. This is a journey. Increase the level over time. Eventually, you will reach a level that feels comfortable. Don't feel sad if you don't have 100% strictness. Some type safety is better than no type safety.
Rely on shortcuts
@ts-ignore and FixMeLater tips can help ease the burden of migration. Not everything needs to be changed at once. Use shortcuts as needed, but don't feel bad about using them. Again, the point is migration, but it shouldn't be very painful. Over time, you can prioritize replacing these with the correct type safety. But remember that these tools are available for you, so use them.
This is not the only way to migrate React projects to TypeScript. However, this works for me. I hope it helps you as much as it helps me.
Further reading
- React with TypeScript: Best Practices
- Practical ways to improve TypeScript skills
- How TypeScript makes you a better JavaScript developer
- JavaScript: From Newbie to Ninja, Second Edition
- React and React Native—Second Edition
Special thanks to Karl Horky, who reached out by explaining that the React.FC
type is not recommended because it has few benefits and has some disadvantages. For more information, see this GitHub discussion.
FAQs on Migrating React Applications to TypeScript
What is TypeScript and why should I consider migrating my React application to it? TypeScript is a statically typed superset of JavaScript that provides enhanced type checking, code quality, and tool support. Migrating to TypeScript can help you catch errors at compile time, improve code maintainability, and enhance the developer experience when dealing with React applications.
How to start migrating my React application to TypeScript? To get started, you can add TypeScript to your project using a tool like Create React App with TypeScript templates, or manually configure your project to support TypeScript. You also need to rename your .js and .jsx files to .ts and .tsx respectively.
What is the process of converting my JavaScript code to TypeScript? This process usually includes: a. Rename your JavaScript file to a TypeScript file with .ts and .tsx extensions. b. Add type comments to your variables, functions, and props. c. Resolve type errors and fix any issues with TypeScript compiler identification. d. Use TypeScript functions such as interfaces and enumerations to define data structures and constants.
Can I move my React application to TypeScript step by step? Yes, you can migrate your application step by step. You can convert components or modules one at a time while maintaining an existing JavaScript code base. This way, you can transition to TypeScript step by step without interrupting your development workflow.
What are the benefits of using TypeScript and React? Some benefits include better code quality, improved developer productivity, enhanced code autocomplete, more powerful refactoring tools, and early detection of common errors. It also provides clearer and more self-documentary code through type annotations.
How to deal with third-party libraries and dependencies when migrating to TypeScript? You can find TypeScript type definition files for many popular libraries (usually with the .d.ts extension) on DefinitelyTyped, or use tools like @types. If the type definition is not available, you can create your own type definition, or use TypeScript's any type to handle untyped libraries.
How to configure my development tools and IDE to use TypeScript in React application? Most popular code editors and IDEs such as Visual Studio Code have great support for TypeScript. You can install TypeScript plugins and extensions for your editor to benefit from enhanced TypeScript integration, autocomplete, and error checking.
What common challenges do I have when migrating to TypeScript? Common challenges include addressing type errors, handling third-party libraries that lack type definitions, understanding TypeScript's type systems, and adapting to stricter type checks that TypeScript enforces.
The above is the detailed content of How to Migrate a React App to TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment
