Book Image

TypeScript Blueprints

By : Ivo Gabe de Wolff
Book Image

TypeScript Blueprints

By: Ivo Gabe de Wolff

Overview of this book

TypeScript is the future of JavaScript. Having been designed for the development of large applications, it is now being widely incorporated in cutting-edge projects such as Angular 2. Adopting TypeScript results in more robust software - software that is more scalable and performant. It's scale and performance that lies at the heart of every project that features in this book. The lessons learned throughout this book will arm you with everything you need to build some truly amazing projects. You'll build a complete single page app with Angular 2, create a neat mobile app using NativeScript, and even build a Pac Man game with TypeScript. As if fun wasn't enough, you'll also find out how to migrate your legacy codebase from JavaScript to TypeScript. This book isn't just for developers who want to learn - it's for developers who want to develop. So dive in and get started on these TypeScript projects.
Table of Contents (16 chapters)
TypeScript Blueprints
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface

Quick example


The following example code shows some basic TypeScript usage. If you understand this code, you have enough knowledge for the next chapters. This example code creates an input box in which you can enter a name. When you click on the button, you will see a personalized greeting:

class Hello { 
  private element: HTMLDivElement; 
  private elementInput: HTMLInputElement; 
  private elementText: HTMLDivElement; 
  constructor(defaultName: string) { 
    this.element = document.createElement("div"); 
    this.elementInput = document.createElement("input"); 
    this.elementText = document.createElement("div"); 
    const elementButton = document.createElement("button"); 
 
    elementButton.textContent = "Greet"; 
 
    this.element.appendChild(this.elementInput); 
    this.element.appendChild(elementButton); 
    this.element.appendChild(this.elementText); 
 
    this.elementInput.value = defaultName; 
    this.greet(); 
 
    elementButton.addEventListener("click", 
      () => this.greet() 
    ); 
  } 
 
  show(parent: HTMLElement) { 
    parent.appendChild(this.element); 
  } 
 
  greet() { 
    this.elementText.textContent = `Hello, 
    ${ this.elementInput.value }!`; 
  } 
} 
 
const hello = new Hello("World"); 
hello.show(document.body); 

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's web page at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/TypeScript_Blueprints. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

The preceding code creates a class, Hello. The class has three properties that contain an HTML element. We create these elements in the constructor. TypeScript has different types for all HTML elements and document.createElement gives the corresponding element type. If you replace div with span (on the first line of the constructor), you would get a type error saying that type HTMLSpanElement is not assignable to type HTMLDivElement. The class has two functions: one to add the element to the HTML page and one to update the greeting based on the entered name.

It is not necessary to specify types for all variables. The types of the variables elementButton and hello can be inferred by the compiler.

You can see this example in action by creating a new directory and saving the file as scripts.ts. In index.html, you must add the following code:

<!DOCTYPE HTML> 
<html> 
  <head> 
    <title>Hello World</title> 
  </head> 
  <body> 
    <script src="scripts.js"></script> 
  </body> 
</html> 

The TypeScript compiler runs on NodeJS, which can be installed from https://nodejs.org. Afterward, you can install the TypeScript compiler by running npm install typescript -g in a console/terminal. You can compile the source file by running tsc scripts.ts. This will create the scripts.js file. Open index.html in a browser to see the result.

The next sections explain the basics of TypeScript in more detail. After reading those sections, you should understand this example fully.

Transpiling

The compiler transpiles TypeScript to JavaScript. It does the following transformations on your source code:

  • Remove all type annotations

  • Compile new JavaScript features for old versions of JavaScript

  • Compile TypeScript features that are not standard JavaScript

We can see the preceding three transformations in action in the next example:

enum Direction { 
  Left, 
  Right, 
  Up, 
  Down 
} 
let x: Direction = Direction.Left; 

TypeScript compiles this to the following:

var Direction; 
(function (Direction) { 
    Direction[Direction["Left"] = 0] = "Left"; 
    Direction[Direction["Right"] = 1] = "Right"; 
    Direction[Direction["Up"] = 2] = "Up"; 
    Direction[Direction["Down"] = 3] = "Down"; 
})(Direction || (Direction = {})); 
var x = Direction.Left; 

In the last line, you can see that the type annotation was removed. You can also see that let was replaced by var, since let is not supported in older versions of JavaScript. The enum declaration, which is not standard JavaScript, was transpiled to normal JavaScript.

Type checking

The most important feature of TypeScript is type checking. For instance, for the following code, it will report that you cannot assign a number to a string:

let x: string = 4; 

In the next sections, you will learn the new features of the latest JavaScript versions. Afterward, we will discuss the basics of the type checker.