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.
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.
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:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
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.
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.
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.
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.
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.
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.
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.
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);
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.
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.
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 }!
.
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.
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.
TypeScript has several primitive types, which are listed in the following table:
Name |
Values |
Example |
boolean |
|
let x: boolean = true;
|
string |
Any string literal |
let x: string = "foo";
|
number |
Any number, including |
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;
|
You can define your own types in various ways:
Kind |
Meaning |
Example |
Object type |
Represents an object, with the specified properties. Properties marked with 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];
|
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.
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.
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.