How to Build React Apps with TypeScript with a Practical Example

John Au-Yeung
Level Up Coding
Published in
13 min readNov 13, 2019

--

Overview

TypeScript is a superset of JavaScript that was created to address many common problems — the biggest being that JavaScript variables and objects have all dynamic types. This means that you have no way to know what properties an object has without logging it in a debugger.

This creates a lot of frustration as you have to check each individual object yourself, slowing down development. Without static types, you also cannot have auto-complete in your editor since there is no way to know what are in those objects are with 100% certainty.

Also, you can put any argument into your JavaScript functions, so there is no enforcement to what is passed in. This creates problems when you pass the wrong argument types expected or don’t pass in enough arguments, making those parameters undefined. There is also nothing stopping you from passing in too many arguments.

By being able to detect all these issues at compile-time, TypeScript makes code easier to understand and follow while decreasing the number of bugs sent to production. You don’t have to worry about breaking things when you change code as the compiler will tell you that you got those basic errors.

Create React App projects can be started with TypeScript using the --typscript option. However, we need to install type definitions for some libraries ourselves.

In this article, we will build an address book app using React and TypeScript.

Getting Started

To start, we need to run Create React App to scaffold the app. We run npx create-react-app address-book --typscript to create the app project folder with the initial files. The app will have a home page to display the contacts and let us open a modal to add a contact. There will be a table that displays all the contacts, and Edit and Delete buttons on each row.

The contacts will be stored in a central MobX store, making them easy to access. React Router will be used for routing. Contacts will be saved in the back end by using the JSON server. We will also use Formik and Yup for form management and validation.

--

--