DEV Community

Cover image for Migrate React App To TypeScript
King Elisha
King Elisha

Posted on

Migrate React App To TypeScript

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

to the following typescript function:

function add(a: number, b: number): number {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
mohammedmahers profile image
Muhammed Maher

Thank you for sharing this, I appreciate the clear short posts!

Collapse
 
elishaking profile image
King Elisha

I'm glad it helped

Collapse
 
venkatvenky97 profile image
venkatesh • Edited

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?