Book Image

Learn React with TypeScript 3

By : Carl Rippon
Book Image

Learn React with TypeScript 3

By: Carl Rippon

Overview of this book

React today is one of the most preferred choices for frontend development. Using React with TypeScript enhances development experience and offers a powerful combination to develop high performing web apps. In this book, you’ll learn how to create well structured and reusable react components that are easy to read and maintain by leveraging modern web development techniques. We will start with learning core TypeScript programming concepts before moving on to building reusable React components. You'll learn how to ensure all your components are type-safe by leveraging TypeScript's capabilities, including the latest on Project references, Tuples in rest parameters, and much more. You'll then be introduced to core features of React such as React Router, managing state with Redux and applying logic in lifecycle methods. Further on, you'll discover the latest features of React such as hooks and suspense which will enable you to create powerful function-based components. You'll get to grips with GraphQL web API using Apollo client to make your app more interactive. Finally, you'll learn how to write robust unit tests for React components using Jest. By the end of the book, you'll be well versed with all you need to develop fully featured web apps with React and TypeScript.
Table of Contents (14 chapters)

Understanding the benefits of TypeScript

When a JavaScript codebase grows, it can become hard to read and maintain. TypeScript is an extension of JavaScript, adding static types. The TypeScript compiler reads in TypeScript code that includes type information and produces clean, readable JavaScript with the type information transformed and removed. The compiled code can then run in our favorite browsers and Node.js.

TypeScript offers several benefits over JavaScript:

  • Coding errors can be caught in the development process earlier
  • Static types allow tools to be built that improve the developer experience and productivity
  • JavaScript features that aren't implemented in all the browsers yet can actually be used in an app that targets those browsers

We'll go through these points in detail in the following sections.

Catching coding errors early

The type information helps the TypeScript compiler catch bugs and typos before our users run into them. In code editors such as Visual Studio Code, a mistake is underlined in red immediately after the user has gone wrong. As an example, create a file called utils.js and paste in the following code, which calculates the total price on an order line:

function calculateTotalPrice(product, quantity, discount) {
var priceWithoutDiscount = product.price * quantity;
var discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}

There is a bug in the code that might be difficult for us to spot. If we open the file in Visual Studio Code, no errors are highlighted. If we change the extension of the file to .ts, Visual Studio Code immediately underlines bits of the code that need our attention in red:

Most of the errors are TypeScript asking for some type information. So, let's add some types to our code:

interface IProduct {
name: string;
unitPrice: number;
}

function calculateTotalPrice(product: IProduct, quantity: number, discount: number): number {
var priceWithoutDiscount: number = product.price * quantity;
var discountAmount: number = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
}

Don't worry if you don't understand what we just added; we'll go through types in the next section. The key point is that we now have a single error highlighted to us, which is, in fact, the bug:

The bug is that our function references a price property in the product object that doesn't exist. The property that we should reference is unitPrice.

Better developer experience and productivity

Let's fix the bug in the previous section by renaming price to unitPrice. Notice how Visual Studio Code gives us IntelliSense lists unitPrice as an option because it looking at our type definition:

Here, TypeScript and Visual Studio Code are using the types to provide a better authoring experience for us. As well as IntelliSense, we are provided with code navigation features, and the safe renaming of functions and variables across multiple files. These features increase our productivity, particularly when the code base is large and there is a team of people working on it.

Using future JavaScript features

There is another benefit of TypeScript that is important to understand. TypeScript allows us to use some features in JavaScript that haven't yet been adopted by all browsers but still target those browsers. TypeScript achieves this by transpiling the use of these features down to JavaScript code that the targeted browser does support.

As an example, let's look at the exponentiation operator (**) in ES7, which isn't supported in IE. Let's create a file called future.ts and enter the following code:

var threeSquared: number = 3 ** 2;
console.log(threeSquared);

When we run the program in a browser, it should put 9 into the console. Before we do that, let's run the code against the TypeScript compiler to get the transpiled JavaScript. Run the following command in a terminal in the same directory as future.ts:

tsc future

This should generate a file called future.js with the following content:

var threeSquared = Math.pow(3, 2);
console.log(threeSquared);

So, TypeScript converted the exponentiation operator to a call to the Math.pow function, which is supported in IE. To confirm that this works, paste the generated JavaScript code into the console in IE and the output should be 9.

This example is purposely simple but probably not that useful. Async/await, spread operators, rest parameters, and arrow functions are far more useful features that IE doesn't support but TypeScript allows the use of. Don't worry if you don't know what the features in the last sentence are, as we'll cover them when we need them in the book.