Ogundipe Samuel software engineer and technical writer

How & why: A guide to using Typescript with React

5 min read 1514


TypeScript is a free, open-source programming language developed and maintained by Microsoft. It is a strict superset of JavaScript and adds optional static typing and class-based object-oriented programming to the language.

TypeScript can be helpful to React developers in a lot of ways.

For example:

  • Interfaces: TypeScript allows you to define complex type definitions in the form of interfaces. This is helpful when you have a complex type that you want to use in your application, such as an object which contains other properties. This results in strict checks which in turn reduces the amount of possible bugs you might have produced without it.
  • TypeScript is very helpful while using IDEs like Visual Studio, Visual Studio Code, Atom, Webstorm, Eclipse and so much more as they provide better autocomplete and snippet generation, which makes development faster.
  • TypeScript makes code easier to read and understand: The key to TypeScript is that it’s a statically typed script. Programming languages can either be statically or dynamically typed; the difference is when type checking occurs. Static languages’ variables are type checked which helps make the code more readable.

Getting Started

To install TypeScript globally so you can call it when needed, run:

npm install -g typescript

For verification of the installed TypeScript, use the tsc — v command:

tsc --v
//Version 2.6.1

Now, create a folder that will hold the application. To do this, run npm init and follow the instructions:

//create a new directory
mkdir typescript-react
//change directory to the new folder
cd typescript-react
//run npm init
npm init

Configuring TypeScript

Given no arguments, tsc will first check tsconfig.json for instructions. When it finds the config, it uses those settings to build the project.

Create a new file called tsconfig.json in the root folder and add:

https://gist.github.com/samuelayo/af08c7741a1e597ac531adbed15dd0f0.js

This defines the two major sections, which include compilerOptions and exclude parameters:

  • In the compiler options, a target of es6 has been set. This means that the JavaScript engine target will be set to es6, and the module will be set to CommonJS. Notice that there is also a key called JSX which is set to react. This Tells typescript to compile jsx files as react files. This is similar to running tsc — jsx react .
  • In the exclude block, node_modules is being defined for it. TypeScript will not scan the node_modules folder for any TypeScript file while compiling.
  • If you are familiar with Typescript and its configuration, you must wonder why the include section is missing. This is because, Webpack will be configured to handle taking in the entry file, passing them to Typescript for compilation and returning a bundled executable for browsers.

Configuring Webpack

First, you need to install Webpack and a Webpack plugin called ts-loader. To do this, run:

npm install webpack ts-loader

Now you may wonder what is ts-loader? Like the name implies, ts-loader is the typescript loader for Webpack. You won’t be wrong to say its a plugin that helps Webpack work well with Typescript.

Just like Typescript, Webpack also checks for a file called webpack.config.js for configuration. So create a new file called webpack.config.js and add:

No Title

No Description

The code base above is simple. Let me explain.

The first key entry refers to the entry point of the application. The app.tsx file referenced here is yet to be created. you will create it soon, hold on.

The output key is an object which accepts two parameters. The first one is the path to publish bundled files, while the second one is the name you want to name your final bundle.

The resolve key is also an object which takes in a key called extensions with an array of extensions it should watch out for and compile.

The module key, which is the last key to talk about is an object which has a key called loaders. The loaders key is an array of objects which defines which Webpack plugin/loader should handle such file.

Here, we test for tsx extensions and ask Webpack to use the ts-loader earlier installed the compilation.

Adding npm Scripts

After all configured so far, wouldn’t it make sense if you could just run a command like npm run magic anytime you want to create a bundle? yes, it would. So, open your package.json file and update your scripts section with:

"scripts": {
   "magic": "webpack"
}

Creating The App.tsx File

Typically, that’s most of the configuration needed. There’s just one more rule to follow all the configuration you have done above: Install types definition for every library you install.

For example, you install react this way:

npm install react @types/react

Install both react and react-dom to start with:

npm install react react-dom @types/react @types/react-dom

Next, create a new file called app.tsx file in the root and add:

No Title

No Description

Above is a simple React setup except that it is using typescript. Move ahead to compile the file by running npm run magic in your terminal. A build folder with a file named bundle.js has been created.

Does this newly created bundle work as expected? Create a new index.html file that references the new build to find out:

No Title

No Description

If you double-click on the index.html file to open in a browser, you will see:

Creating a component

You know you’ve got the basics of writing React in Typescript when you have your first page ready. Now it’s time to dive into writing React Components.

First, create a new folder called src as this is where components will live in. Next, create a file called FirstComponent.tsx and paste:

No Title

No Description

The above code-block is a simple component that returns a logo and some text. To make this new component accessible to React, you need to import and use the component in the base app.tsx file. Alter your app.tsx file to:

No Title

No Description

Looking at the code-block above, you see that the differences are on line 3 and 7 respectively, where you imported the new component and also rendered it.

If you run the npm run magic command, and you navigate to your browser, you will see:

Using Typescript interfaces with component

One of TypeScript’s core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”.

In TypeScript, interfaces fill the role of naming these types and are a powerful way of defining contracts within your code and contracts with code outside of your project.

First, create a new file in the src folder called UserInterface.ts and add:

No Title

No Description

The code block above defines a simple User interface, which I will pass in as props into a new component. Because this interface is strongly typed, notice you cannot pass an integer for the name key as the value is a string.

Declare a new component called UserComponent.tsx in the src folder and add:

No Title

No Description

The code block above is self-explanatory. I have imported the UserInterface created earlier on, passed it as the props of the UserComponent. In the constructor, I re-check that the props passed in, are of the UserInterface type. In the render function, I printed the details out.

Next, Alter your app.tsx file to:

No Title

No Description

If you run the npm run magic command, and you navigate to your browser, you will see:

Conclusion

In this tutorial, you have (hopefully) learned how to use Typescript with Reactjs. You have also learnt how to configure Webpack with ts-loader to compile the Typescript files and emit a final build.

The code base for this tutorial is available here. Play around with it.


Plug: LogRocket, a DVR for web apps

LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single page apps.

Ogundipe Samuel software engineer and technical writer

Leave a Reply