React is a world-popular JavaScript library, which developers use worldwide to do frontend. It is a great tool for creating lightweight user interfaces and is also fit to build complex apps. However, the program expands with new functionality over time and becomes increasingly difficult to maintain and manage. And here, TypeScript comes to our aid.

TypeScript extends JavaScript and improves the developer experience. It enables developers to add a type of safety to their projects. Using TypeScript allows us to get the benefits of IntelliSense and the ability to further reason about our code. As well as this, adopting TypeScript is low-friction, as files can be incrementally upgraded without causing issues throughout the rest of your project. TypeScript is a syntactic superset of JavaScript that adds static typing. This basically means that TypeScript adds syntax on top of JavaScript, allowing developers to add types. TypeScript is a “Syntactic Superset”, it has the same base syntax as JavaScript but adds something to it.

In this article, we’ll look into why you should use TypeScript in your React applications and see some code examples that illustrate these benefits. Also, we’ll consider how to simply add a Typescript to the existing React project or setup project from the template.

5 benefits of combining Typescript with React

Type Safety

TypeScript ensures safety while writing the code. TypeScript guarantees type-checking while compiling. It removes many errors like typos or using null/undefined objects, methods, and properties; it also gives visible data definitions during the program flow. By catching errors early, you can save yourself a lot of time and effort in debugging. In JavaScript, you can easily pass incorrect data types to functions, which can cause runtime errors. For example, let’s take a look at the following code:

How to use Typescript in your React Project

 

As we can see, the add() function takes two arguments: a and b, and returns their sum. We can accidentally pass a string instead of a number as a second parameter, and the function will still return a value, even though it’s not what we expected.

Using TypeScript, we can define the types of parameters and then return the value of the function. Here’s how we can write the same function with TypeScript:

How to use Typescript in your React projects

 

We’ve added types to the function parameters and return value. If we now try to pass a string instead of a number to the add() function, TypeScript will catch the error while compiling and prevent us from running the code. This helps to catch errors early.

Better IDE Support

TypeScript provides better IDE support than JavaScript. IDEs like Visual Studio Code can analyze your TypeScript code and provide auto-complete, code navigation, and refactoring tools. For example, let’s say we have the following code:

How to use Typescript in your React projects

 

As we can see above, we’ve defined an interface for User that describes data and also a function greet() that takes a User object and returns us a greeting. We’ve also defined an object user with additional properties that aren’t part of the User interface.

If we try to call the greet() function with the object user, we’ll get an error because the object has properties that aren’t described in the User interface.

Visual Studio Code can describe the error, allowing us to navigate to the part of the code that’s causing the error.

Improved Code Quality

TypeScript’s language provides features like interfaces and classes that can easily help us write more structured, efficient, and organized code. Let’s take a look at this example:

How to use Typescript in your React projects

 

Here, we’ve defined a User interface that describes the shape of data and a class UserComponent that takes a user prop with the User type. In addition, we’ve defined the render() method that renders the user’s name, age, and email on the screen.

With TypeScript, we can ensure that the user prop always has the correct type, and we can leverage interfaces and classes to create more maintainable and reusable code. This can improve code quality and make it easier to refactor.

Easier Refactoring

TypeScript can also make it easier to refactor your code during development. Assuming we have the code below:

How to use Typescript in your React projects

 

We’ve defined a User interface and a function greet() that takes a User object and returns a greeting.

We want to change the greet() function to take a firstName and lastName instead of a name property in the User interface. In JavaScript, we need to update all the calls to the greet() function manually; this can be time-consuming and cause unnecessary errors. However, using TypeScript, it is easy to rename the name property to firstName and lastName and let the TypeScript compiler find all the calls to the greet():

How to use Typescript in your React projects

 

The TypeScript compiler will find all the calls to the greet() function and highlight all the places where the name property is used instead of firstName and lastName. This saves a lot of time and reduces the risk of any bugs during the refactoring process.

Better Documentation

Finally, using TypeScript in React applications can help to do better documentation. By defining types for our variables, state, and other props, we can make code more self-documenting and easier to understand for other developers that may also work with it. There is no need to write unclear comments. For example, let’s say we have a component that renders a single user:

How to use Typescript in your React projects

 

In this code, we’ve defined a User interface that describes our data and an interface called UserProps that describes the shape of props. We’ve also defined a functional component UserDetail(), that takes a user prop with the User type.

By using TypeScript along with React, we can see the expected shape of our props and the types of variables at a glance. It makes it easier for developers to understand the code, especially if they are unfamiliar with the specific implementation.

Need a reliable partner for developing your next React project with Typescript? Leobit is here to help.

How To Create a React Project With TypeScript From Template

To create a React project with TypeScript, you can use Create React App with the TypeScript option. Here are the steps to create a project:

1. Install Node.js and npm if they are not already installed on your computer.

2. Open a terminal and type the following command to install Create React App:

How to use Typescript in your React projects

3. Then you need to create a new project with the TypeScript option, enter the following command in the terminal:

How to use Typescript in your React projects

 

4. Once you’ve finished creating your project, navigate to its folder. To do this, type a command:

How to use Typescript in your React projects

 

5. So now you can run the project with the following command:

How to use Typescript in your React projects

6. That’s it! Open a browser and go to http://localhost:3000 to check if your project works. Now you’re ready to build your React project with TypeScript! Fire up your code editor and start programming.

How To Add TypeScript to an Existing React Project

If you already have a React project without TypeScript, you can add TypeScript support by installing the necessary dependencies and modifying some project files. Here are the steps you need to follow:

  1. Install the required dependencies for TypeScript. Open a terminal and enter the following command:
    How to use Typescript in your React projects

 

  1. Create a TypeScript configuration file. Open a terminal and enter the following command. This command will create a file tsconfig.json where you can configure your TypeScript compilation settings:
    How to use Typescript in your React projects

 

  1. Rename all files .js to .tsx. If you have JavaScript files in your React project, rename them to TypeScript files with the extension .tsx.
  1. Replace React.Component with React.FC. If you have React components that inherit from React.Component, replace them with function components (React.FC).
  1. Check your props. Check that all props in your React project have types, and add types if needed.

After completing these steps, your React project has TypeScript support! Now you can use TypeScript in your project and get the benefits of static typing.

Conclusion

To summarize, there are a lot of advantages to using TypeScript with React, including better IDE support (e.g. Visual Code), type safety, and simple refactoring. It can aid in early error detection, make a project’s codebase more understandable, and enhance code quality. It is strongly recommended that you try TypeScript if you’re considering using it in your React projects!