Reader small image

You're reading from  Learn React with TypeScript - Second Edition

Product typeBook
Published inMar 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781804614204
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Carl Rippon
Carl Rippon
author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon

Right arrow

Introducing TypeScript

In this chapter, we will start by understanding what TypeScript is and how it provides a much richer type system on top of JavaScript. We will learn about the basic types in TypeScript, such as numbers and strings, and then learn how to create our own types to represent objects and arrays using different TypeScript features. Finally, we will finish the chapter by understanding the TypeScript compiler and its key options in a React app.

By the end of the chapter, you’ll be ready to learn how to use TypeScript to build frontends with React.

In this chapter, we’ll cover the following topics:

  • Understanding the benefits of TypeScript
  • Understanding JavaScript types
  • Using basic TypeScript types
  • Creating TypeScript types
  • Using the TypeScript compiler

Technical requirements

We will use the following technologies in this chapter:

  • Browser: A modern browser such as Google Chrome.
  • TypeScript Playground: This is a website at https://www.typescriptlang.org/play/ that allows you to play around with and understand the features of TypeScript without installing it.
  • CodeSandbox: We’ll briefly use this online tool to explore JavaScript’s type system. This can be found at https://codesandbox.io/.
  • Visual Studio Code: We’ll need an editor to experience TypeScript’s benefits and explore the TypeScript compiler. This one can be installed from https://code.visualstudio.com/. Other editors that could be used can be found at https://github.com/Microsoft/TypeScript/wiki/TypeScript-Editor-Support.
  • Node.js and npm: TypeScript is dependent on these pieces of software. You can install them from https://nodejs.org/en/download/.

All the code snippets in this chapter can be found online at https...

Understanding the benefits of TypeScript

In this section, we will start by understanding what TypeScript is, how it relates to JavaScript, and how TypeScript enables teams to be more productive.

Understanding TypeScript

TypeScript was first released in 2012 and is still being developed, with new releases happening every few months. But what is TypeScript, and what are its benefits?

TypeScript is often referred to as a superset or extension of JavaScript because any feature in JavaScript is available in TypeScript. Unlike JavaScript, TypeScript can’t be executed directly in a browser – it must be transpiled into JavaScript first.

Note

It is worth being aware that a proposal is being considered that would allow TypeScript to be executed directly in a browser without transpilation. See the following link for more information: https://github.com/tc39/proposal-type-annotations.

TypeScript adds a rich type system to JavaScript. It is generally used with frontend...

Understanding JavaScript types

Before understanding the type system in TypeScript, let’s briefly explore the type system in JavaScript. To do this, open the CodeSandbox at https://codesandbox.io/ and carry out the following steps:

  1. Create a new plain JavaScript project by choosing the Vanilla option.
  2. Open index.js, remove its content, and replace it with the following code:
    let firstName = "Fred"
    console.log("firstName", firstName, typeof firstName);
    let score = 9
    console.log("score", score, typeof score);
    let date = new Date(2022, 10, 1);
    console.log("date", date, typeof date);

The code assigns three variables to various values. The code also outputs the variable values to the console, along with their JavaScript type.

Here’s the console output:

Figure 2.5 – Some JavaScript types

Figure 2.5 – Some JavaScript types

It isn’t surprising that firstName is a string and score is a number. However, it is a little...

Using basic TypeScript types

In this section, we’ll start by understanding how TypeScript types can be declared and how they are inferred from assigned values. We will then learn the basic types commonly used in TypeScript that aren’t available in JavaScript and understand helpful use cases.

Using type annotations

TypeScript type annotations enable variables to be declared with specific types. These allow the TypeScript compiler to check that the code adheres to these types. In short, type annotations allow TypeScript to catch bugs where our code uses the wrong type much earlier than we would if we were writing our code in JavaScript.

Open the TypeScript Playground at https://www.typescriptlang.org/play and carry out the following steps to explore type annotations:

  1. Remove any existing code in the left-hand pane and enter the following variable declaration:
    let unitPrice: number;

The type annotation comes after the variable declaration. It starts...

Creating TypeScript types

The last section showed that TypeScript has a great set of standard types. In this section, we will learn how to create our own types. We will start by learning three different methods for creating object types. We will then learn about strongly-typing JavaScript classes. Lastly, we will learn two different methods for creating types for variables that hold a range of values.

Using object types

Objects are very common in JavaScript programs, so learning how to represent them in TypeScript is really important. In fact, we have already used an object type earlier in this chapter for the product parameter in the calculateTotalPrice function. Here is a reminder of the product parameter’s type annotation:

function calculateTotalPrice(
  product: { name: string; unitPrice: number },
  ...
) {
  ...
}

An object type in TypeScript is represented a bit like a JavaScript object literal. However, instead of property values...

Using the TypeScript compiler

In this section, we will learn how to use the TypeScript compiler to type check code and transpile it into JavaScript. First, we will use Visual Studio Code and create a simple TypeScript project containing code we have written in a previous section. We will then use the terminal within Visual Studio Code to interact with the TypeScript compiler.

Open Visual Studio Code in a blank folder of your choice, and carry out the following steps:

  1. In the EXPLORER panel in Visual Studio Code, create a file called package.json containing the following content:
    {
      "name": "tsc-play",
      "dependencies": {
        "typescript": "^4.6.4"
      },
      "scripts": {
        "build": "tsc src/product.ts"
      }
    }

The file defines a project name of tsc-play and sets TypeScript as the only dependency. The file also...

Summary

TypeScript complements JavaScript with a rich type system, and in this chapter, we experienced catching errors early using TypeScript’s type checking.

We also learned that JavaScript types, such as number and string, can be used in TypeScript, as well as types that only exist in TypeScript, such as Date and unknown.

We explored union types and learned that these are great for representing a specific set of strings. We now understand that string enumerations are an alternative to string union types if the string values aren’t very meaningful.

New types can be created using type aliases. We learned that type aliases could be based on objects, functions, or even union types. We now know that the ? symbol in a type annotation makes an object property or function parameter optional.

We also learned a fair bit about the TypeScript compiler and how it can work well in different use cases because it is very configurable. This will be important when we start...

Questions

Answer the following questions to check what you have learned about TypeScript:

  1. What would the inferred type be for the flag variable in the following code?
    let flag = false;
  2. What is the return type in the following function?
    function log(message: string) {
      return console.log(message);
    }
  3. What is the type annotation for an array of dates?
  4. Will a type error occur in the following code?
    type Point = {x: number; y: number; z?: number};
    const point: Point = { x: 24, y: 65 };
  5. Use a type alias to create a number that can only hold integer values between and including 1 and 3.
  6. What TypeScript compiler option can be used to prevent the transpilation process when a type error is found?
  7. The following code raises a type error because lastSale can’t accept null values:
    type Product = {
      name: string;
      lastSale: Date;
    }
    const table: Product = {name: "Table", lastSale: null}

How can the Product type be changed...

Answers

  1. The flag variable would be inferred to be a boolean type.
  2. The return type in the function is void.
  3. An array of dates can be represented as Date[] or Array<Date>.
  4. A type error will not be raised on the point variable. It doesn’t need to include the z property because it is optional.
  5. A type for numbers 1-3 can be created as follows:
    type OneToThree = 1 | 2 | 3;
  6. The noEmitOnError compiler option (set to true) can be used to prevent the transpilation process when a type error is found.
  7. A union type can be used for the lastSale property to allow it to accept null values:
    type Product = {
      name: string;
      lastSale: Date | null;
    }
    const table: Product = {name: "Table", lastSale: null}
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React with TypeScript - Second Edition
Published in: Mar 2023Publisher: PacktISBN-13: 9781804614204
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon