The aim of this tutorial is to teach you the steps to convert a ReactJS application written in Javascript into a ReactJS application that supports TypeScript. This tutorial will not into go into the pros & cons of TypeScript. This post is a practical no-nonsense instruction manual that will hopefully inspire you to give it a try. This tutorial will outline the code, config and file change you will need to make in order to get going. To get started we obviously need TypeScript installed:

Next, create a file called tsconfig.json in your application root. This file will configure how TypeScript behaves. If you want the application to run both Javascript and Typescript, you need to set allowJs=true. You will also need to set jsx=react.

If you are using web-pack, you will need to provide TypeScript file extension support:

When adding TypeScript you may also want to add support for linting and code formatting. If you use lint-staged, prettier and eslint then you will need to add some TypeScript specific config within 'package.json', like this:

If you use eslint' within your .eslintrc file, add TypeScript file extension support:

After you have the correct config the steps to convert a component from JS to TypeScript are:

  • Rename a component from a file extension from 'js' to 'tsx'
  • If the component has a corresponding test, rename the test files extension from 'js' to 'ts'
  • Within the component, remove any prop-types
  • Create an interface for the components
  • Implement the interface on the class

An example of how to create and implement TypeScript interface for a simple functional component is shown below:

To implement an interface on a class component is done like this (although I recommend converting functional component!):

Now you have converted one file, go forth and multiply! Happy coding!