Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
TypeScript Blueprints
TypeScript Blueprints

TypeScript Blueprints: Practical Projects to Put TypeScript into Practice

Arrow left icon
Profile Icon de Wolff
Arrow right icon
$29.99 $43.99
eBook Jul 2016 288 pages 1st Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon de Wolff
Arrow right icon
$29.99 $43.99
eBook Jul 2016 288 pages 1st Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

TypeScript Blueprints

Chapter 1. TypeScript 2.0 Fundamentals

In Chapters 2 through 5, we will learn a few frameworks to create (web) applications with TypeScript. First you need some basic knowledge of TypeScript 2.0. If you have used TypeScript previously, then you can skim over this chapter, or use it as a reference while reading the other chapters. If you have not used TypeScript yet, then this chapter will teach you the fundamentals of TypeScript.

What is TypeScript?

The TypeScript language looks like JavaScript; it is JavaScript with type annotations added to it. The TypeScript compiler has two main features: it is a transpiler and a type checker. A transpiler is a special form of compiler that outputs source code. In case of the TypeScript compiler, TypeScript source code is compiled to JavaScript code. A type checker searches for contradictions in your code. For instance, if you assign a string to a variable, and then use it as a number, you will get a type error.

The compiler can figure out some types without type annotations; for others you have to add type annotations. An additional advantage of these types is that they can also be used in editors. An editor can provide completions and refactoring based on the type information. Editors such as Visual Studio Code and Atom (with a plugin, namely atom-typescript) provide such features.

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.

Learning modern JavaScript

JavaScript has different versions. Some of these are ES3, ES5, ES2015 (also known as ES6), and ES2016. Recent versions are named after the year in which they were introduced. Depending on the environment for which you write code, some features might be or might not be supported. TypeScript can compile new features of JavaScript to an older version of JavaScript. That is not possible with all features, however.

Recent web browsers support ES5 and they are working on ES2015.

We will first take a look at the constructs that can be transpiled to older versions.

let and const

ES2015 has introduced let and const. These keywords are alternatives to var. These prevent issues with scoping, as let and const are block scoped instead of function scoped. You can use such variables only within the block in which they were created. It is not allowed to use such variables outside of that block or before its definition. The following example illustrates some dangerous behavior that could be prevented with let and const:

alert(x.substring(1, 2)); 
var x = "lorem"; 
for (var i = 0; i < 10; i++) { 
  setTimeout(function() { 
    alert(i); 
  }, 10 * i); 
} 

The first two lines give no error, as a variable declared with var can be used before its definition. With let or const, you will get an error, as expected.

The second part shows 10 message boxes saying 10. We would expect 10 messages saying 0, 1, 2, and so on up to 9. But, when the callback is executed and alert is called, i is already 10, so you see 10 messages saying 10.

When you change the var keywords to let, you will get an error in the first line and the messages work as expected. The variable i is bound to the loop body. For each iteration, it will have a different value. The for loop is transpiled as follows:

var _loop_1 = function(i) { 
    setTimeout(function () { 
        alert(i); 
    }, 10 * i); 
}; 
for (var i = 0; i < 10; i++) { 
    _loop_1(i); 
} 

A variable declared with const cannot be reassigned, and a variable with let can be reassigned. If you reassign a const variable, you get a compile error.

Classes

As of ES2015, you can create classes easily. In older versions, you could simulate classes to a certain extent. TypeScript transpiles a class declaration to the old way to simulate a class:

class Person { 
  age: number; 
   
  constructor(public name: string) { 
     
  } 
   
  greet() { 
    console.log("Hello, " + this.name); 
  } 
} 
 
const person = new Person("World"); 
person.age = 35; 
person.greet(); 

This example is transpiled to the following:

var Person = (function () { 
    function Person(name) { 
        this.name = name; 
    } 
    Person.prototype.greet = function () { 
        console.log("Hello, " + this.name); 
    }; 
    return Person; 
}()); 
var person = new Person("World"); 
person.age = 35; 
person.greet(); 

When you prefix an argument of the constructor with public or private, it is added as a property of the class. Other properties must be declared in the body of the class. This is not per the JavaScript specification, but needed with TypeScript for type information.

Arrow functions

ES6 introduced a new way to create functions. Arrow functions are function expressions defined using =>. Such function looks like the following:

(x: number, y: boolean): string => { 
  statements 
} 

The function expression starts with an argument list, followed by an optional return type, the arrow (=>), and then a block with statements. If the function has only one argument without type annotation and no return type annotation, you may omit the parenthesis: x => { ... }. If the body contains only one return statement, without any other statements, you can simplify it to (x: number, y: number) => expression. A function with one argument and only a return statement can be simplified to x => expression.

Besides the short syntax, arrow functions have one other major difference with normal functions. Arrow functions share the value of this and the position where it was defined; this is lexically bound. Previously, you would store the value of this in a variable called _this or self, or you would fix the value using .bind(this). With arrow functions, that is not required any more.

Function arguments

It is possible to add a default value to an argument:

function sum(a = 0, b = 0, c = 0) { 
  return a + b + c; 
} 
sum(10, 5); 

When you call this function with less than three arguments, it will set the other arguments to 0. TypeScript will automatically infer the types of a, b, and c based on their default values, so you do not have to add a type annotation there.

You can also define an optional argument without a default value: function a(x?: number) {}. The argument will then be undefined when it is not provided. This is not standard JavaScript, but only available in TypeScript.

The sum function can be defined even better, with a rest argument. At the end of a function, you can add a rest argument:

function sum(...xs: number[]) { 
  let total = 0; 
  for (let i = 0; i < xs.length; i++) total += xs[i]; 
  return total; 
} 
sum(10, 5, 2, 1); 

Array spread

It is easier to create arrays in ES6. You can create an array literal (with brackets), in which you use another array. In the following example, you can see how you can add an item to a list and how you can concatenate two lists:

const a = [0, 1, 2]; 
const b = [...a, 3]; 
const c = [...a, ...b]; 

A similar feature for object literals will probably be added to JavaScript too.

Destructuring

With destructuring, you can easily create variables for properties of an object or elements of an array:

const a = { x: 1, y: 2, z: 3 }; 
const b = [4, 5, 6]; 
 
const { x, y, z } = a; 
const [u, v, w] = b; 

The preceding is transpiled to the following:

var a = { x: 1, y: 2, z: 3 }; 
var b = [4, 5, 6]; 
 
var x = a.x, y = a.y, z = a.z; 
var u = b[0], v = b[1], w = b[2]; 

You can use destructing in an assignment, variable declaration, or argument of a function header.

Template strings

With template strings, you can easily create a string with expressions in it. If you would write "Hello, " + name + "!", you can now write Hello ${ name }!.

New classes

ES2015 has introduced some new classes, including Map, Set, WeakMap, WeakSet, and Promise. In modern browsers, these classes are already available. For other environments, TypeScript does not automatically add a fallback for these classes. Instead, you should use a polyfill, such as es6-shim. Most browsers already support these classes, so in most cases, you do not need a polyfill. You can find information on browser support at http://caniuse.com.

Type checking

The compiler will check the types of your code. It has several primitive types and you can define new types yourself. Based on these types, the compiler will warn when a value of a type is used in an invalid manner. That could be using a string for multiplication or using a property of an object that does not exist. The following code would show these errors:

let x = "foo"; 
x * 2; 
x.bar(); 

TypeScript has a special type, called any, that allows everything; you can assign every value to it and you will never get type errors. The type any can be used if you do not have an exact type (yet), for instance, because it is a complex type or if it is from a library that was not written in TypeScript. This means that the following code gives no compile errors:

let x: any = "foo"; 
x * 2; 
x.bar(); 

In the next sections, we will discover these types and learn how the compiler finds these types.

Primitive types

TypeScript has several primitive types, which are listed in the following table:

Name

Values

Example

boolean

true, false

let x: boolean = true;   

string

Any string literal

let x: string = "foo";   

number

Any number, including Infinity, -Infinity, and NaN

let x: number = 42;   
let y: number = NaN;   

Literal types

Literal types can only contain one value

let x: "foo" = "foo";   

void

Only used for a function that does not return a value

function a(): void { }   

never

No values

any

All values

let x: any = "foo";   
let y: any = true;   

Defining types

You can define your own types in various ways:

Kind

Meaning

Example

Object type

Represents an object, with the specified properties. Properties marked with ? are optional. Objects can also have an indexer (for example, like an array), or call signatures.

Object types can be defined inline, with a class or with an interface declaration.

let x: {   
  a: boolean,   
  b: string,   
  c?: number,   
  [i: number]: string   
};   
x = {   
  a: true, b: "foo" };   
x[0] = "foo";   

Union type

A value is assignable to a union type if it is assignable to one of the specified types. In the example, it should be a string or a number.

let x: string | number;   
x = "foo";   
x = 42;   

Intersection type

A value is assignable to an intersection type if it is assignable to all specified types.

let x: { a: string } & { b:   number } = { a: "foo", b: 42 };   

Enum type

A special number type, with several values declared. The declared members get a value automatically, but you can also specify a value.

enum E {   
  X,   
  Y = 100   
}   
let a: E = E.X;   

Function type

Represents a function with the specified arguments and return type. Optional and rest arguments can also be specified.

let f: (x: string, y?: boolean)   => number;   
let g: (...xs: number[]) =>   number;   

Tuple type

Multiple values are placed in one, as an array.

let x: [string, number];   
X = ["foo", 42];   

Undefined and null

By default, undefined and null can be assigned to every type. Thus, the compiler cannot give you a warning when a value can possibly be undefined or null. TypeScript 2.0 has introduced a new mode, called strictNullChecks, which adds two new types: undefined and null. With that mode, you do get warnings in such cases. We will discover that mode in Chapter 6, Advanced Programming in TypeScript.

Type annotations

TypeScript can infer some types. This means that the TypeScript compiler knows the type, without a type annotation. If a type cannot be inferred, it will default to any. In such a case, or in case the inferred type is not correct, you have to specify the types yourself. The common declarations that you can annotate are given in the following table:

Location

Can it be inferred?

Examples

Variable declaration

Yes, based on initializer

let a: number;   
let b = 1;   

Function argument

Yes, based on default value (second example) or when passing the function to a typed variable or function (third example)

function a(x: number) {}   
function b(x = 1) {}   
[1, 2].map(   
  x => x * 2   
);   

Function return type

Yes, based on return statements in body

function a(): number { }   
(): number => { }   
function c() {   
  return 1;   
}   

Class member

Yes, based on default value

class A {   
  x: number;   
  y = 0;   
}   

Interface member

No

interface A {   
  x: number;   
}   

You can set the compiler option noImplicitAny to get compiler errors when a type could not be inferred and falls back to any. It is advised to use that option always, unless you are migrating a JavaScript codebase to TypeScript. You can read about such migration in Chapter 10,Migrate JavaScript to TypeScript.

Summary

In this chapter, you discovered the basics of TypeScript. You should now be familiar with the principles of TypeScript and you should understand the code example at the beginning of the chapter. You now have the knowledge to start with the next chapters, in which you will learn two major web frameworks, Angular 2 and React. We will start with Angular 2 in Chapter 2, A Weather Forecast Widget with Angular 2.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Follow and build every featured projects to put the principles of TypeScript into practice
  • Learn how to use TypeScript alongside other leading tools such as Angular 2, React, and Node.js
  • Find out how to migrate your JavaScript codebase to TypeScript

Description

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.

Who is this book for?

This is for web developers committed to building better software. It's for web developers that know writing code should be fun - and that fun and creativity are the foundations of better software products.

What you will learn

  • Build quirky and fun projects from scratch
  • Use TypeScript with a range of different technologies such as Angular 2 and React
  • Migrate JavaScript codebases to TypeScript to improve your workflow
  • Write maintainable and reusable code
  • Using System.JS and Webpack to load scripts and their dependencies.
  • Developing highly performance server-side applications to run within Node.js
  • Reviewing high performant Node.js patterns and manage garbage collection

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 28, 2016
Length: 288 pages
Edition : 1st
Language : English
ISBN-13 : 9781785888779
Vendor :
Microsoft
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 28, 2016
Length: 288 pages
Edition : 1st
Language : English
ISBN-13 : 9781785888779
Vendor :
Microsoft
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 98.98
TypeScript Blueprints
$54.99
TypeScript Design Patterns
$43.99
Total $ 98.98 Stars icon

Table of Contents

10 Chapters
1. TypeScript 2.0 Fundamentals Chevron down icon Chevron up icon
2. A Weather Forecast Widget with Angular 2 Chevron down icon Chevron up icon
3. Note-Taking App with a Server Chevron down icon Chevron up icon
4. Real-Time Chat Chevron down icon Chevron up icon
5. Native QR Scanner App Chevron down icon Chevron up icon
6. Advanced Programming in TypeScript Chevron down icon Chevron up icon
7. Spreadsheet Applications with Functional Programming Chevron down icon Chevron up icon
8. Pac Man in HTML5 Chevron down icon Chevron up icon
9. Playing Tic-Tac-Toe against an AI Chevron down icon Chevron up icon
10. Migrate JavaScript to TypeScript Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.