Use Typescript in an already existing create-react-app Project

Add typescript to an existing create-react-app project

You have started learning TypeScript and may have even applied it to a react project by using the npx create-react-app — typescriptflag or set up a react project from scratch using tools such as webpack, babel, etc.

Now you feel comfortable using the typescript language and want to go back to some oldcreate-react-app and add some types to your code using typescript but don’t know how to go about it?

This was actually the main reason for writing this blog. Enough of the storytelling, let’s get busy!

First of all, I assume you have node and npm already installed as well as a text editor of your choice(preferably: vscode)

  1. The first step is to open your create-react-project (created with javascript) with any text editor of your choice.
  2. Next, open the terminal(Mac and Linux users) or command line(window users) and make sure you’re in your project’s directory.
  3. Install the following packages by running: npm i typescript @types/node @types/react @types/react-dom
running npm command to install typescript and other types

4. In the end, you should have the following packages in your package.json file:

The reason for installing @types/react @types/react-dom is, it gives us access to some type definitions out of the box, defined by developers at React for building their components.

  • Change a javascript extension file .js to a typescript extension .ts or if the file extension is .jsx, change it to .tsx. In my case, I’m going to change my App.jsx file to App.tsx
  • Start the development server by running npm start. A prompt will show in your terminal notifying you that a tsconfig file has been set up and populated with default values.
prompt showing that a tsconfig.json file has been created
  • Finally, you should see a tsconfig.json file in your project structure. You can modify the values in this file to suit whatever that you’re doing.

This approach is not suitable for large projects with several javascript files. I’m not saying it’s not possible but this approach is tedious and error-prone.

If you have any suggestions to improve this blog, kindly comment below. Also, you can reach me on twitter at victorbruce3

A Software Engineer who loves to share his knowledge through writing