reacttypescriptHow TypeScript helps you build better React apps

In which situations should you give React with TypeScript a try, and when is it better to stick to JavaScript? Speaking of my own experience, I walk you through the pros and cons of a TypeScript based frontend.

In which situations should you give React with TypeScript a try, and when is it better to stick to JavaScript?

Speaking of my own experience, I walk you through the pros and cons of a TypeScript based React frontend.

Welcome to the first part of this guide, where I teach how to use React with TypeScript!

In this guide, I want to teach you everything you need to know about using React with TypeScript. Over the next weeks, I'll publish new articles to this guide, so if you want to get notified about my latest content, make sure to subscribe to my newsletter.

In this first article, I want to introduce you to TypeScript and look at the pros and cons of adding it to a React project.

What is TypeScript?

[TypeScript] is a strict syntactical superset of JavaScript and adds optional static typing to the language.

The definition is taken from Wikipedia.

The definition above condenses in one sentence what TypeScript is all about.

But let's have a look at what this actually means.

A strict syntactical superset of JavaScript means that TypeScript expands the JavaScript programming language without altering the existing syntax.

TypeScript understands any JavaScript syntax, which means that we can use a combination of JavaScript and TypeScript in our project, making migrating a lot easier.

The second part of the definition states that TypeScript adds optional static typing to the language.

Static typing is the most important advantage of using TypeScript. We can add types to the functions and variables in our application.

Often, TypeScript can infer a variable's type by looking at the value we use to initialize it.

The compiler will throw an error if we try to assign a value of the wrong type to this variable.

let name = '';
name = 123;

Even though the syntax didn't change, the TypeScript compiler will throw an error in this case.

Speaking of compilers, TypeScript doesn't have native browser support, and browser vendors have no plans to add support.

TypeScript compiles all code into JavaScript. You can configure your project to target any ECMA version that you want. The compiler will make sure that your code is compatible with the version you selected.

TypeScript will typically compile any file that ends with ts or tsx (for React's JSX syntax) and compile these into JavaScript.

ReactJS is typically used together with Babel, which compiles the JSX code and browser compatibility.

When migrating to TypeScript, you won't need Babel anymore as the compiler can handle both of these tasks.

Advantages of using React with TypeScript

Now that you know what TypeScript is about let's look at the benefits a typed language provides.

Autocompletion

Having autocompletion is a considerable advantage that you will notice right after writing your first React component with TypeScript.

You won't need to check what the state looks like or what props your component accepts; your editor will automatically suggest the right properties while you're typing.

TypeScript autocompletion example

What were the fields of that object again? TypeScript tells me everything I need to know without changing context, even in the VIM editor using coc.vim.

In the case that you did forget a prop of a component, your editor will warn you.

TypeScript React error

When I worked with plain JavaScript, I had difficulties remembering the parameters that each function accepts, and related errors were more common than I’d like to admit.

Autocompletion frees up the cognitive load used for remembering props and function parameters, which allows you to focus more on building the application.

Compile-time errors

Given that we're talking about using React with TypeScript, you probably already used Babel to compile your application.

TypeScript compiles your code as well, but with a much tighter net for catching errors.

By default, errors will appear in the terminal, and you can configure your project to abort the compilation when the compiler finds an error.

This behavior is useful in combination with a CI pipeline as it prevents type errors from going to production.

The better type-safety you have in your project, the more you will benefit from this.

ESNext and TypeScript features

Like Babel, TypeScript also implements some features flagged as experimental according to the ECMA standard.

For instance, they were the first to introduce optional chaining in version 3.7, which allows you to safely access properties of an object that can be null or undefined.

Previously, you'd need to write something like the following if you only wanted to access baz if foo and bar exist.

foo && foo.bar && foo.bar.baz();

With optional chaining, you can achieve the same using the ? operator.

foo?.bar?.baz();

Optional chaining is just one of many features that TypeScript implements but don't use this if you don't want to have types in your application; you can also use Babel for this.

Both TypeScript and Babel can compile ESNext features into JavaScript code that is compatible with most browsers.

Disadvantages of using React with TypeScript

As with everything, there are also some downsides to TypeScript, of which you should be aware.

Based on this, you can decide for yourself if it's worth putting up with these disadvantages to get the advantages I mentioned above.

If in doubt, it might be worth giving it a try with a smaller project to test the waters.

You need to do the work first

Especially when migrating an existing project, you can't just set up the TypeScript compiler and expect to have a more stable codebase right away.

TypeScript can infer the type in some cases, but this isn't enough.

To get the most out of this, you'll need to put in the effort to migrate your existing .jsx files.

The good thing, though is, that you don't need to do everything at once. As mentioned earlier, TypeScript is a superset of JavaScript, so it's possible to use JavaScript and TypeScript together.

You can incrementally get your codebase to be 100% TypeScript, with incremental releases each time you finish migrating a few files.

You need to write more code

I feel like this is one of the main reasons people don't want to move to TypeScript. They're afraid that TypeScript makes them write a lot of boilerplate code.

While it is true that you'll need to write additional code, I think the overhead is minimal.

If we were to compare the amount of code to a pure JavaScript codebase, I would argue that with TypeScript, you may end up writing less code.

Why? Simply because pure JavaScript requires you to write more extensive unit tests to make up for the lack of types. You don't need to write tests that verify primitive data types anymore.

This doesn't mean that you don't need to write tests, but your tests can now focus on testing functionality.

Missing type definitions for some libraries

Most of the libraries I've used in the last years either ship with their type definitions, or they can be installed as a separate npm package.

However, there are a few that don't have type definitions. If you come across such a library, you will usually need to create your own definitions.

This isn't optimal and can be very time intensive if done correctly.

I usually create a definition file that only covers the functionalities that I use in my project.

It has become increasingly rare to find a library with no definitions, though, so this point shouldn't hold you back from using TypeScript.

Type-safety can (sometimes) be a pain in the ass

Last, I have to say that despite all the advantages, type-safety can be annoying sometimes and cause more work initially.

While this doesn't apply to the code you write yourself, I've worked with libraries (like MobX-State-Tree), where the type definitions were sometimes hard to work with. Finding the right type can involve quite a bit of research if you want to get it right.

const names = ['John', 'Doe'] as IMSTArray<ISimpleType<string>>;

Arrays in MST models are complex types, so string[] doesn't suffice in some cases.

Conclusion

You've now seen my breakdown of the pros and cons of using TypeScript and React.

While TypeScript is no silver bullet for more stable frontends with React, it has some strong arguments in its favor.

Decide for yourself whether you want to use it or not. I encourage you to give it a try with a smaller project of yours first if you're not sure yet.

In case you already have experience with TypeScript and React, please to leave a comment with your take on the subject!

Get notified about new tutorials

Join over 1,000 developers who receive React and JavaScript tutorials via email.

No spam. Unsubscribe at any time.