Healthcare Software Systems

The Benefits of Using TypeScript with React

By Engineering Team July 2, 2019 10 mins read

JavaScript is one of the core technologies used on the web today. In the past, JavaScript was used by web developers to allow the creation of customizable and interactive web pages. However, since the advent of NodeJS and a multitude of front-end and back-end frameworks, it’s use has far exceeded the original intended purpose.

Introducing TypeScript

JavaScript is a scripting language. The coding is loosely typed and notoriously challenging to debug on large scale applications. In contrast, C# and Java are compiled languages, with rich debuggers and descriptive compile-time errors. Tools such as document formatters and linters for JavaScript can be useful for keeping your code clean, however, the problem of type-checking still remains. This is where TypeScript comes in.

According to the official website,

  • “TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.”

Let’s break that down. Typescript is a ‘superset’ of JavaScript. In layman’s terms, Typescript has all the features of JavaScript and more. It’s also ‘typed’, which means you can assign types to variables in your code. (I’ll explain that last part later in the article.)

It also compiles to plain JavaScript, which means you can use it as little as you want (or as much as you want) and it will work with your existing code-base.

How Does TypeScript Work with React?

In React, you have to maintain different variables including states, props, and member functions (if you’re using class components). As the size of your application increases, it becomes harder and harder to keep track of everything. With TypeScript, a simple solution is to look at the definition (or if your IDE supports it, hover over the variable) and find out the variable type. TypeScript supports lots of other features including type inference, generators, etc. But for the purpose of this article, we’ll stick to implementing basic type checking.

Installing TypeScript

There are two ways to get up and running with TypeScript.

  1. Run a one-liner. Running this one line creates a simple folder structure for your application, installs all the required modules, and gets you up and running in an instant. Simply, run this command. create-react-app name-of-app –scripts-version=react-scripts-ts

This is fairly straightforward, especially if you’ve already used Create React App.

With the exception of a few files such as tsconfig.json, the folder structure will look similar to a regular React CRA application. This is where you define the configuration for your TypeScript environment. Notice the use of the .tsx extension, instead of a .jsx. This is important because you’ll be using this extension for all the files you want to compile into regular JavaScript.

  1. In the second method, you set everything up manually. A detailed list of these steps can be found in the official documentation.

The idea is since TypeScript has to compile regular JavaScript, you need to use a loader (such as awesome-typescript-loader) with webpack to handle this step. One helpful tip is it’s better to use the TypeScript version of common libraries. Note, TypeScript versions for all libraries are not yet available, so be sure to check this before you get too far along. To add TypeScript, you must prefix the name of the library with ‘@types/‘. Once everything is set into place, you can start using TypeScript immediately.

Let’s take a look at how this works by creating a component.

TypeScript encourages us to define the access modifiers for our member functions as “public” for the render function.

Now, let’s import it into the App.tsx file and pass props to it.

You should get an error that says type “place” is not assignable. Here, TypeScript is taking over and telling you that you have not defined any props for this component, or that the props defined in the component are different from what you’re passing through.

To correct this error, create an interface for your props.

State that you are only expecting one prop, of type string. The “?” declares this prop to be optional.

Then you can add to our component to enable the interface.

Interfaces are virtual structures that only exist to validate our code. They are removed during compile-time as JavaScript does not support them.

In the case of functions, you can provide the type of a parameter by adding “: Type” after the name of the parameter, where ‘Type’ is a TypeScript supported type such as number, boolean, string, void, etc. You may also provide an interface here. Moreover, you may add on to the basic types. For example, to define an array of strings you can use Array<string>. The full list of types is available here.

The above component can be converted into a stateless component.

To add a return type to functions add “: Type” after the parameters.

Now let’s add state to our class component.

You’ll simply create another interface called IState, and add it to the class component just like you did for IProps.

If you were to give the ‘fruit’ variable any other type, the TypeScript compiler would most likely throw an error.

For example, if “Type ‘number’ is not assignable to type ‘string,’” pops up, you’ve come across an error.

You may also define defaultProps for your component.

Here, you are using the same interface defined for your props earlier.

Let’s try to create an input field and connect it to our state.

To do this, you must provide the ‘React.ChangeEvent<HTMLInputElement>’ type to the event parameter.

This will ensure that you’re passing through the event type expected by the event handler.

If you don’t want to specify a type, for times like these you can simply give it the ‘any’ type, which works the same way as if you were not using types at all.

More Work Up Front Means Less Work Later

At first glance, using TypeScript may seem like you’re writing more code for little benefit, but this is far from true. TypeScript does require you to write more code initially, but this is meant to help avoid the pitfalls of the loosely typed nature of JavaScript, resulting in spending hours debugging later, fixing avoidable mistakes. And thanks to interoperability between both languages, TypeScript is only usable when you see fit. This makes TypeScript ideal for any medium to large scale project.

The Benefits Outweigh the Negatives

For most developers, the benefits of using TypeScript outweigh the negatives. Although it may seem cryptic at first, we recommend using types in JavaScript until it becomes second nature. This is possible with a little bit of practice. With fewer errors and bugs to fix in the long run, you’ll be left wondering how you were ever able to program your previous applications without any static typing.