© Adam Freeman 2019
A. FreemanEssential TypeScripthttps://doi.org/10.1007/978-1-4842-4979-6_2

2. Understanding TypeScript

Adam Freeman1 
(1)
London, UK
 

TypeScript is a superset of the JavaScript language that focuses on producing safe and predictable code that can be executed by any JavaScript runtime. Its headline feature is static typing, which makes working with JavaScript more predictable for programmers familiar with languages such as C# and Java. In this book, I explain what TypeScript does and describe the different features it provides.

This Book and The Typescript Release Schedule

The TypeScript team makes frequent releases, which means there is an ongoing stream of fixes and features. It doesn’t seem fair or reasonable to ask you to buy a new edition of this book every few months, especially since the majority of TypeScript features are unlikely to change even in a major release. Instead, I am going to post updates following the major releases to the GitHub repository for this book, https://github.com/Apress/essential-typescript .

This is an ongoing experiment for me (and for Apress), and I don’t yet know what form those updates may take—not least because I don’t know what the major releases of TypeScript will contain—but the goal is to extend the life of this book by supplementing the examples it contains.

I am not making any promises about what the updates will be like, what form they will take, or how long I will produce them before folding them into a new edition of this book. Please keep an open mind and check the repository for this book when new TypeScript versions are released. If you have ideas about how the updates could be improved, then e-mail me at [email protected] and let me know.

Should You Use TypeScript?

TypeScript isn’t the solution to every problem, and it is important to know when you should use TypeScript and when it will simply get in the way. In the sections that follow, I describe the high-level features that TypeScript provides and the situations in which they can be helpful.

Understanding the TypeScript Developer Productivity Features

TypeScript’s headline features are focused on developer productivity, especially through the use of static types, which help make the JavaScript type system easier to work with. Other productivity features, such as access control keywords and a concise class constructor syntax, help prevent common coding errors.

The TypeScript productivity features are applied to JavaScript code. As Chapter 1 demonstrated, the TypeScript package includes a compiler that processes TypeScript files and produces pure JavaScript that can be executed by a JavaScript runtime, such as Node.js or a browser, as shown in Figure 2-1.
../images/481342_1_En_2_Chapter/481342_1_En_2_Fig1_HTML.png
Figure 2-1.

The TypeScript transformation to JavaScript code

The combination of JavaScript and TypeScript features retains much of the flexible and dynamic nature of JavaScript while constraining the use of data types so they are familiar and more predictable for most developers. It also means that projects that use TypeScript can still make use of the wide range of third-party JavaScript packages that are available, either to provide specific features (such as the command-line prompts in Chapter 1) or to embrace complete frameworks for app development (such as the React, Angular, and Vue.js frameworks described in Part 3).

TypeScript features can be applied selectively, which means you can use only those features useful for a specific project. If you are new to TypeScript and JavaScript, you are likely to start by using all of the TypeScript features. As you become more experienced and your depth of knowledge increases, you will find yourself using TypeScript with more focus and applying its features just to the parts of your code that are especially complex or that you expect to cause problems.

Understanding the Limitations of the Productivity Features

Some TypeScript features are implemented entirely by the compiler and leave no trace in the JavaScript code that is executed when the application runs. Other features are implemented by building on standard JavaScript and performing additional checks during compilation. This means you often have to understand how a feature works and how it is implemented to get the best results, which can make TypeScript features seem inconsistent and arcane.

More broadly, TypeScript enhances JavaScript, but the result is still JavaScript, and development in a TypeScript project is largely a process of writing JavaScript code. Some developers adopt TypeScript because they want to write web applications without learning how JavaScript works. They see that TypeScript is produced by Microsoft and assume that TypeScript is C# or Java for web development, which is an assumption that leads to confusion and frustration.

Effective TypeScript requires a good knowledge of JavaScript and the reasons it behaves as it does. Chapters 3 and 4 describe the JavaScript features you need to understand to get the best out of TypeScript and provide a solid foundation for understanding why TypeScript is such a powerful tool.

If you are willing to understand the JavaScript type system, then you will find TypeScript a pleasure to use. But if you are not willing to invest the time to become competent in JavaScript, then you should not use TypeScript. Adding TypeScript to a project when you don’t have any JavaScript knowledge makes development more difficult because you will have two sets of language features to wrangle, neither of which will behave exactly as you expect.

Understanding the JavaScript Version Features

JavaScript has had a turbulent history but has recently become the focus of a concerted standardization and modernization effort, introducing new features that make JavaScript easier to use. The problem is that there are still lots of JavaScript runtimes that don’t support these modern features, especially older browsers, which constrains JavaScript development to the small set of language features that are universally supported. JavaScript can be a challenging language to master, and this is made worse when the features intended to make development easier cannot be used.

The TypeScript compiler is able to transform JavaScript code written using modern features into code that conforms to older versions of the JavaScript language. This allows recent JavaScript features to be used with TypeScript during development while allowing older JavaScript runtimes to execute the code that the project produces.

Understanding the Limitations of the Version Features

The TypeScript compiler does a good job of dealing with most language features, but there are some features that just can’t be translated effectively for older runtimes. If the earliest versions of JavaScript are your target, you will find that not all modern JavaScript features can be used during development because the TypeScript compiler doesn’t have the means to represent them in legacy JavaScript.

That said, the need to generate legacy JavaScript code isn’t important in all projects because the TypeScript compiler is just one part of an extended toolchain. The TypeScript compiler is responsible for applying the TypeScript features, but the result is modern JavaScript code that is further processed by other tools. This approach is commonly used in web application development, and you will see examples in Part 3.

What Do You Need to Know?

If you decide that TypeScript is the right choice for your project, then you should be familiar with using data types in development and understand the basic JavaScript features. Don’t worry if you do not understand how JavaScript deals with data types, however, because I provide a primer for all the JavaScript features that are useful to understand TypeScript in Chapters 3 and 4. In Part 3 of this book, I demonstrate how TypeScript can be used with popular web application development frameworks, and knowledge of HTML and CSS is required for these examples.

How Do You Set Up Your Development Environment?

The only development tools needed for TypeScript development are the ones you installed in Chapter 1 when you created your first application. Some later chapters require additional packages, but full instructions are provided. If you successfully built the application in Chapter 1, then you are set for TypeScript development and for the rest of the chapters in this book.

What Is the Structure of This Book?

This book is split into three parts, each of which covers a set of related topics.
  • Part 1, “Getting Started with TypeScript”: Part 1 of this book provides the information you need to get started with TypeScript development. It includes Chapter 1, this chapter, and a primer chapter for the data type features provided by JavaScript. Chapters 5 and 6 introduce the TypeScript development tools.

  • Part 2, “Understanding TypeScript”: Part 2 of this book covers the TypeScript features for developer productivity, including static types. TypeScript provides a lot of different type features, which I describe in depth and demonstrate with examples.

  • Part 3, “Creating Applications with TypeScript”: TypeScript isn’t used on its own, so Part 3 of this book shows you how to use TypeScript to create web applications using three popular frameworks: React, Angular, and Vue.js. These chapters explain the TypeScript features that are useful for each framework and demonstrate how to achieve tasks commonly required during web application development. To provide the foundation for understanding what these frameworks do, I also show you how to create a stand-alone web application that doesn’t rely on a web application framework.

Are There Lots of Examples?

There are loads of examples. The best way to learn TypeScript is by example, and I have packed as many of them into this book as I can. To maximize the number of examples in this book, I have adopted a simple convention to avoid listing the same code or content repeatedly. When I create a file, I will show its full contents, just as I have in Listing 2-1. I include the name of the file and its folder in the listing’s header, and I show the changes that I have made in bold.
function calculateTax(amount: number, format: boolean): string | number {
    const calcAmount = amount * 1.2;
    return format ? `$${calcAmount.toFixed(2)}` : calcAmount;
}
let taxValue = calculateTax(100, false);
switch (typeof taxValue) {
    case "number":
        console.log(`Number Value: ${taxValue.toFixed(2)}`);
        break;
    case "string":
        console.log(`String Value: ${taxValue.charAt(0)}`);
        break;
    default:
        let value: never = taxValue;
        console.log(`Unexpected type for value: ${value}`);
}
let newResult: unknown = calculateTax(200, false);
let myNumber: number = newResult as number;
console.log(`Number value: ${myNumber.toFixed(2)}`);
Listing 2-1.

Asserting an Unknown Value in the index.ts File in the src Folder

This is a listing from Chapter 7, which shows the contents of a file called index.ts that can be found in the src folder. Don’t worry about the content of the listing or the purpose of the file; just be aware that this type of listing contains the complete contents of a file and that the changes you need to make to follow the example are shown in bold.

Some files can be long when the feature that I am describing requires only a small change. Rather than list the complete file, I use an ellipsis (three periods in series) to indicate a partial listing, which shows just a portion of the file, as shown in Listing 2-2.
...
"scripts": {
  "json": "json-server data.js -p 4600",
  "serve": "react-scripts start",
  "start": "npm-run-all -p serve json",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
},
...
Listing 2-2.

Configuring Tools in the package.json File in the reactapp Folder

This is a listing from Chapter 19, and it shows a set of changes applied to one part of a larger file. When you see a partial listing, you will know that the rest of the file does not have to change and that only the sections marked in bold are different.

In some cases, changes are required in different parts of a file, which makes it difficult to show as a partial listing. In this situation, I omit part of the file’s contents, as shown in Listing 2-3.
import { Product, Order } from "./entities";
import { minimumValue } from "../decorators";
export type ProductProp = keyof Product;
export abstract class AbstractDataSource {
    private _products: Product[];
    private _categories: Set<string>;
    public order: Order;
    public loading: Promise<void>;
    constructor() {
        this._products = [];
        this._categories = new Set<string>();
        this.order = new Order();
        this.loading = this.getData();
    }
    @minimumValue("price", 30)
    async getProducts(sortProp: ProductProp = "id",
            category? : string): Promise<Product[]> {
        await this.loading;
        return this.selectProducts(this._products, sortProp, category);
    }
    // ...other methods omitted for brevity...
}
Listing 2-3.

Applying a Decorator in the abstractDataSource.ts File in the src Folder

In this listing from Chapter 16, the changes are still marked in bold, and the parts of the file that are omitted from the listing are not affected by this example.

Where Can You Get the Example Code?

You can download the example projects for all the chapters in this book from https://github.com/Apress/essential-typescript . The download is available without charge and contains everything that you need to follow the examples without having to type in all of the code.

Where Can You Get Corrections for This Book?

You can find errata for this book at https://github.com/Apress/essential-typescript .

How Can You Contact Me?

If you have problems making the examples in this chapter work or if you find a problem in the book, then you can e-mail me at [email protected], and I will try my best to help. Please check the errata for this book to see whether it contains a solution to your problem before contacting me.

Summary

In this chapter, I explained when TypeScript is a good choice for projects. I also outlined the content and structure of this book, explained where to get the source code, and talked about how to contact me if you have problems with the examples in this book. In the next chapter, I give you a primer for the JavaScript type system, which provides the underpinnings for the features of TypeScript.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.178.207