For react projects created with create-react-app, it is very easy to migrate to Typescript. This will guarantee type checking and proper linting of the codebase.
Steps
1. Install necessary dependencies
# yarn
yarn add -D typescript @types/node @types/react-dom @types/jest @types/react-router-dom
# npm
npm install --save-dev typescript @types/node @types/react-dom @types/jest @types/react-router-dom
Note: most react/npm packages will require an @types/<package-name>
dependency to work with typescript. So add them accordingly
2. Change file extensions
- Change component files from
.js
or.jsx
to.tsx
- Change other javascript files from
.js
to.ts
- Fix import statements
- Fix any other issues that may arise
Since react works with es6 syntax, switching to typescript should raise minimal to no issues
3. Start project
# yarn
yarn start
# npm
npm start
Starting the project will automatically create a tsconfig.json
file with all the necessary settings
4. Add Type to variables and functions
Append the type for each variable, parameter and return type for each function or method.
For example, change the following javascript function:
function add(a, b) {
return a + b;
}
to the following typescript function:
function add(a: number, b: number): number {
return a + b;
}
Both parameters in the function have a type of number
and the function also has a return type of number
5. Define Classes/Interfaces for Complex Data
This includes data from API's and redux state
Thanks π for making it to the end π¨βπ» and I really hope you found the content useful.
Leave a comment below or tweet me @ElishaChibueze if you have any questions or suggestions
Top comments (3)
Thank you for sharing this, I appreciate the clear short posts!
I'm glad it helped
hi bro i want one help as i did hotstar clone single page application by using react and redux then i want to refactor to typescript..how to convert react with javascript to react with typescript?