Type Script Training
Type Script Training
All rights reserved. No part of this book can be reproduced or stored in any retrieval system, or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without
the prior written permission of the Dot Net Tricks.
The authors of this book have tried their best to ensure the accuracy of the information described in this book.
However, the authors cannot guarantee the accuracy of the information contained in this book. The authors will
not be liable for any damages, incidental or consequential caused directly or indirectly by this book. Further,
readers should be aware that the websites or reference links listed in this book may have changed or disappeared
between when this book was written and when it is read.
All other trademarks referred to in this book are the property of their respective owners.
Release History
Initial Release 1.0.0 - 18th Jan 2017
1
Page
Dedication
My mother Mrs. Vriksha Devi and my wife Reshu Chauhan deserve to have theirs name on the cover as
much as I do for all theirs support made this possible. I would like to say thanks to all my family members
Virendra Singh(father), Jaishree and Jyoti(sisters), Saksham and Pranay(sons), friends, to you and to
readers or followers of my blog www.dotnettricks.com to encourage me to write this book.
-Shailendra Chauhan
My mother Anjna puri deserve to have theirs name on the cover as much as I do for all theirs support
made this possible. I would like to say thanks to all my family members Radhika Puri (wife), Natasha
Gulati(sister) and Yogeshwar Puri(father), friends, to encourage me to write this.
-Kanishk Puri
2
Page
Introduction
His inspiration for authoring come from his enthusiasm for technology, analytic and initiative nature. Being a
trainer, architect and blogger and passion for helping people inspire him for writing.
Kanishk Puri is a Full Stack Developer and Mobile Developer working on wide set of web Technologies for more
than 6 years. He has vast experience on C#, ASP.NET, JavaScript, Node.js, No SQL Database, Angular, Angular2 and
Hybrid App, and a few more technologies.
Enormous feedback and support from the previous books which appreciated by all users inspire us to write
TypeScript Training book.
To get the latest release on TypeScript, we encourage you to follow the official TypeScript website at
www.typescriptlang.org
3
Page
Our best wishes always with you for your learning and growth!
About the Authors
Shailendra is the author of some of most popular e-books which encompass technical Interview on Node.js
Interview Questions and Answers, AngularJS Interview Questions and Answers, LINQ Interview Questions and
Answers and MVC Interview Questions and Answers. Furthermore, he is a technical reviewer for book on ASP.NET
MVC 4 Mobile App Development.
Shailendra Chauhan is renowned for sharing his working experience, research and knowledge through his reputed
and widely subscribed to blogs - www.dotnettricks.com and www.gurukulsight.com. Specifically, his blog
www.dotnettricks.com provides a vast storehouse of knowledge and support resources in the field of .NET
technologies worldwide and is listed as a non-Microsoft resource in The Microsoft Official Community Site. His
blogs and training approach provide an easily accessible and highly innovative learning experience for people
everywhere, and from a range of backgrounds and skill levels thereby offering the ultimate in training around the
world.
Moreover, and to his credit he has delivered 200+ training sessions to professionals world-wide in Microsoft .NET
technologies and other technologies including JavaScript, AngularJS, Node.js, Ionic and NoSQL Databases. In
addition, he provides Instructor-led online and classroom training programs for all above technologies.
Shailendra’s strong combination of technical skills and solution development for complex application
architecture with proven leadership and motivational skills have elevated him to a world-renowned status,
placing him at the top of the list of most sought-after trainers.
“I always keep up with new technologies and learning new skills to deliver the best to my students” says
Shailendra Chauhan, he goes on to acknowledge that the betterment of his followers and enabling his students to
realize their goals are his prime objective and a great source of motivation and satisfaction.
4
Shailendra Chauhan - “Follow me and you too will have the key that opens the door to success”
Page
Kanishk Puri - Full Stack Developer and Mobile Developer
He is a Full Stack Developer working on wide set of web Technologies for
more than 6 years. He has vast experience on C#, ASP.NET, JavaScript,
Node.js, No SQL Database, Angular, Angular2 and Hybrid App, and a few
more technologies.
In the past 3 years, He has shifted his interest from Full Stack Developer to Mobile Web and App Development.
After that, He started developing Mobile Web and Apps with the leading technologies like Ionic, Angular, Angular2,
Web API, Xamarin and Native script.
Shailendra Chauhan is one of the best friend of Kanishk Puri, encourage him to share his experiences with
developers. After that he decided to become co-author of this book. And now he feels great to share his
experiences.
Kainshk Puri – “There is no elevator to success, you have to take the stairs”
5
Page
How to Contact Us
Although the author of this book has tried to make this book as accurate as it possible but if there is something
strikes you as odd, or you find an error in the book please drop a line via e-mail.
shailendra@dotnettricks.com
info@dotnettricks.com
I am always happy to hear from my readers. Please provide with your valuable feedback and comments!
You can follow us on facebook, twitter, linkedin and google plus or subscribe to RSS feed.
6
Page
Our Most Accepted Training Programs by Professionals
Node.js Development
About the Course Download Course Agenda
The Node.js Development course is primarily designed for UI Developer(s)/Web Developer(s) who want to learn
how to develop high performance, event-driven, real-time and scalable networking and web applications. In this
course, you will learn the Node.js, Express, Bootstrap, Unit Testing and JavaScript Task runner (Grunt, Gulp)
fundamental like JavaScript event loop, express routes, unit test cases, HTTP web server, handle requests &
responses, event-driven communications, handling databases and much more...
Course objectives
At the completion of this course, attendees will be able to;
Describe JavaScript weird parts like prototype, objects, lexical scope, dynamic scope and closure.
Explore Node.js basic and advanced in-depth concepts.
Create and consume REST API.
Create HTTP web server and handling requests & responses.
Handle Sessions, Cookies, and Session Stores.
Perform Node.js database operations with SQL and NoSQL Databases.
Write Unit Test cases using Jasmine/Mocha and Chai.
Use HTML Template engines like Handlebars and Jade.
Install and Publish Node's Package Manager – NPM.
Use JS Task runner like Gulp or Grunt.
Publish their Node.js App on cloud server Heroku.
Course objectives
At the completion of this course, attendees will be able to;
Course objectives
At the completion of this course, attendees will be able to;
Course objectives
At the completion of this course, attendees will be able to;
Course objectives
At the completion of this course, attendees will be able to;
Course objectives
At the completion of this course, attendees will be able to;
Course objectives
At the completion of this course, attendees will be able to;
Introduction ......................................................................................................................................................... 18
Page
Advantages of TypeScript .................................................................................................................................... 18
TypeScript based JavaScript Frameworks ........................................................................................................... 18
Tools And IDE....................................................................................................................................................... 19
Getting Started with TypeScript using Visual Studio Code.................................................................................. 19
Install TypeScript using NPM ........................................................................................................................... 20
Open Visual Studio Code ................................................................................................................................. 20
Setting TypeScript compilation option in Visual Studio Code ......................................................................... 21
Creating Task to Transpile TypeScript into JavaScript ..................................................................................... 21
Running Code using Node ............................................................................................................................... 23
Important Information .................................................................................................................................... 23
TypeScript Compilation ....................................................................................................................................... 23
ECMAScript 3 (ES3) .......................................................................................................................................... 23
ECMAScript 5 (ES5) .......................................................................................................................................... 24
ECMAScript 6 (ES6) .......................................................................................................................................... 24
Types ............................................................................................................................. 25
Introduction ......................................................................................................................................................... 25
Any Type .............................................................................................................................................................. 25
Primitive Types .................................................................................................................................................... 26
Number ............................................................................................................................................................ 26
Boolean ............................................................................................................................................................ 26
String................................................................................................................................................................ 27
Void.................................................................................................................................................................. 27
Null................................................................................................................................................................... 28
Undefined ........................................................................................................................................................ 28
Symbols............................................................................................................................................................ 29
Enum ................................................................................................................................................................ 29
Object Types ........................................................................................................................................................ 31
Array ................................................................................................................................................................ 31
Tuple ................................................................................................................................................................ 31
Function ........................................................................................................................................................... 32
15
Class ................................................................................................................................................................. 32
Interface .......................................................................................................................................................... 33
Page
Template Strings .................................................................................................................................................. 34
Type Annotation .................................................................................................................................................. 34
Type Inference ..................................................................................................................................................... 35
Type Assertion ..................................................................................................................................................... 36
Statements .................................................................................................................... 37
Introduction ......................................................................................................................................................... 37
Variable Statement .............................................................................................................................................. 37
Variable Declaration using var, let and const ...................................................................................................... 37
Block Scoping ....................................................................................................................................................... 38
Hoisting................................................................................................................................................................ 38
Important Information .................................................................................................................................... 39
Destructuring ....................................................................................................................................................... 39
If, do..while, while and for Statements ............................................................................................................... 40
For..In Statement................................................................................................................................................. 40
For..Of Statement ................................................................................................................................................ 41
Operators............................................................................................................................................................. 41
Functions ....................................................................................................................... 42
Introduction ......................................................................................................................................................... 42
Optional Parameters ........................................................................................................................................... 42
Default Parameters ............................................................................................................................................. 43
Rest Parameters .................................................................................................................................................. 44
Spread Operator .................................................................................................................................................. 45
Function Overloads.............................................................................................................................................. 46
Arrow Function .................................................................................................................................................... 47
Classes ........................................................................................................................... 49
Introduction ......................................................................................................................................................... 49
Constructors ........................................................................................................................................................ 50
Instance and Static Members .............................................................................................................................. 51
Access Modifiers .................................................................................................................................................. 53
16
Accessors ............................................................................................................................................................. 55
Inheritance .......................................................................................................................................................... 57
Abstract Class ...................................................................................................................................................... 59
Interfaces ....................................................................................................................... 61
Introduction ......................................................................................................................................................... 61
Use of Interfaces.................................................................................................................................................. 61
Interface Inheritance ........................................................................................................................................... 62
Class Implementing Interfaces ............................................................................................................................ 62
Interface Extending Class .................................................................................................................................... 63
Generics ......................................................................................................................... 64
Introduction ......................................................................................................................................................... 64
Generic Functions ................................................................................................................................................ 64
Generic Classes .................................................................................................................................................... 65
Generic Interfaces ............................................................................................................................................... 67
Decorators ..................................................................................................................... 73
Introduction ......................................................................................................................................................... 73
Class Decorator.................................................................................................................................................... 73
Method Decorator ............................................................................................................................................... 73
Property Decorator.............................................................................................................................................. 74
Important Information .................................................................................................................................... 74
Typescript 1.0 was released on 1st Oct, 2012 by Microsoft as a free and open source programming
language for JavaScript based enterprise application development. At the time of writing this book, the
latest version of TypeScript was 2.0.
If you or your team come from a strongly typed language like C#, Java and Php then you don’t need to
learn JavaScript syntax and style to develop your JavaScript application; TypeScript is a good alternative.
Since it will give you the feel of object-oriented programming language.
Advantages of TypeScript
Simplify JavaScript code which is easier to read and debug.
Provides Type Safety at compile time.
Unlike JavaScript, it supports classes, Interfaces etc.
Supports latest standard and evolving features of JavaScript including ES5 and ES6.
Supports modularity.
Open source.
applications as well as hybrid and native mobile apps. Some of the frameworks are shown in the fig.
Page
Source: www.typescriptlang.org
Source: www.typescriptlang.org
Node.js
Page
Command Prompt
Create a new file named as hello.ts by clicking New File option in the MyProject row of the explore
sidebar as given below:
20
Page
Add following line of code as given below:
Hello.ts
class Program {
constructor(private msg: string) {
}
showDetails() {
console.log("Your message is : " + this.msg);
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true
}
}
This shows a selection box with templates you can choose from. Choose TypeScript – tsconfig.json option and
press Enter.
22
Page
It’s time to execute the task. It can be executed by simply pressing Ctrl+Shift+B (Run Build Task). At this
point you will see an additional file show up in the file list with name hello.js.
Command Prompt
Node hello
Important Information
TypeScript never executed by browser, so you have to add reference of compiled JS file
(Generated by TypeScript compiler) to your webpage.
TypeScript code can be compiled as per ES3 standard to support older browser.
TypeScript code can be compiled as per ES5 and ES6 standard to support latest browser.
A piece of JavaScript code is a valid TypeScript code.
TypeScript Compilation
TypeScript is compiled into JavaScript and JavaScript is an implementation of the ECMAScript standard.
Version 4 of the ECMAScript specification was abandoned, so technically it does not exist.
You can compile your TypeScript code into three versions of ECMAScript – ES3, ES5 and ES6. When you
deal with browsers, you should know the browsers supports for all these ECMAScript standards.
ECMAScript 3 (ES3)
ECMAScript 3 standard was published in 1999 and it is widely supported by all the browsers available
in market. If you are targeting ES3 compilation for your TypeScript file, limited number of TypeScript
23
features are supported. But it offers the widest support for your code in all the browsers.
Page
ECMAScript 5 (ES5)
ECMAScript 5 standard was published in Dec, 2009 and it is widely supported by all the latest browsers
available in market. If you are targeting ES5 compilation for your TypeScript file, maximum number of
TypeScript features are supported. ES5 is supported in the following browsers:
Chrome 7 or higher
FF 4 or higher
IE 9 or higher
Opera 12 or higher
Safari 5.1 or higher
ECMAScript 6 (ES6)
ECMAScript 6 standard was published in June, 2015 and its features are only supported by the latest
browsers. If you are targeting ES6 compilation for your TypeScript file, all the TypeScript features are
supported but your code might not work in older browsers like IE7, IE8, IE9 and IE10. ES6 is supported
in the following browsers:
Chrome 30 or higher
FF 20 or higher
IE 11, Edge 12 or higher
Opera 15 or higher
Safari 7 or higher
For detailed analysis of ES5 and ES6 features support by the browsers, please refer the given link:
https://goo.gl/YmLnMl
24
Page
Types
Introduction
TypeScript is referred to as optional static type language which means you can ask the compiler to ignore
the type of a variable if you want to take the advantage of dynamic type. This mixing of static and
dynamic typing is also available in C# where you can define the static typed using primary datatype and
secondary datatype and also you can define the dynamic type using the dynamic keyword.
Here, we will discuss about the TypeScript Types which you can use to write your TypeScript code.
Any Type
The Any type is a supertype of all types which represents any JavaScript value. You can assign any type
of value to it. The any keyword is used to define Any type in TypeScript.
The Any type is useful, when we do not know the type of value (which might come from an API or a 3rd
party library) and we want to skip the type-checking on compile time.
any.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
any.js
function ProcessData(x, y) {
return x + y;
}
var result;
result = ProcessData("Hello ", "Any!"); //Hello Any!
25
Number
The Number primitive type is equivalent to JavaScript primitive type number, which represents double
precision 64-bit floating-point values. The number keyword is used to define Number type in TypeScript.
TypeScript supports decimal, hexadecimal, binary and octal literals.
number.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
number.js
var nondecimal = 2;
var decimal = 2.4;
var hexadecimal = 0xf;
var binary = 4;
var octal = 7;
Boolean
The Boolen primitive type is equivalent to JavaScript primitive type boolen which accepts a value that is
either true or false. The boolean keyword is used to define Boolean type in TypeScript.
boolen.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
boolen.js
26
var no = false;
String
The String primitive type is equivalent to JavaScript primitive type string and represents the sequence of
characters stored as Unicode UTF-16 code units. The string keyword is used to define String type in
TypeScript.
Just like JavaScript, TypeScript also uses double quotes (") or single quotes (') to surround string data.
string.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
string.js
Void
The Void primitive type represents the absence of a value. The void keyword is used to define Void type
in TypeScript but it is not useful because you can only assign null or undefined values to it.
The void type is mostly used as a function return type that does not return a value or as a type argument
for a generic class or function.
void.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
void.js
function displayMeassge() {
console.log("Welcome to Gurukulsight!");
}
var unusable = undefined;
27
Page
Null
The Null primitive type is equivalent to JavaScript primitive type null which accepts the one and only
value null. The null keyword is used to define Null type in TypeScript but it is not useful because you can
only assign null value to it.
The Null type is a subtype of all types except the undefined type. Hence, you can assign null as a value
to all primitive types, object types, union types, and type parameters.
null.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
null.js
Undefined
The Undefined primitive type is equivalent to JavaScript primitive type undefined and all uninitialized
variables in TypeScript and JavaScript have one and only value that is undefined. The undefined keyword
is used to define Undefined type in TypeScript but it is not useful because you can only assign undefined
value to it.
The Undefined type is also a subtype of all types. Hence, you can assign undefined as a value to all
primitive types, object types, union types, and type parameters.
undefined.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
Page
undefined.js
Symbols
A symbol is a new, primitive data type introduced in ES6 just like number and string. A symbol value is
created by calling the Symbol constructor.
symbols1.ts
let s1 = Symbol();
let s2 = Symbol("mySymbol");
Symbols are immutable, and unique. When you create two symbols with the same description then they will be
unique and immutable. Just like strings, symbols can be used as keys for object properties.
symbols2.js
Enum
An enum is a way to give friendly names to a set of numeric values. The enum keyword is used to define
Enum type in TypeScript. By default, the value of enum’s members start from 0. But you can change this
by setting the value of one of its members.
enum.ts
enum.js
var Courses;
(function (Courses) {
Courses[Courses["TypeScript"] = 0] = "TypeScript";
Courses[Courses["Ionic"] = 1] = "Ionic";
Courses[Courses["Angular2"] = 2] = "Angular2";
Courses[Courses["NodeJS"] = 3] = "NodeJS";
})(Courses || (Courses = {}));
;
var tscourse = Courses.TypeScript;
console.log(tscourse); //0
In the previous example, we can start the enum’s members value from 2 instead of 0.
enum.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
enum.js
var Courses;
(function (Courses) {
Courses[Courses["TypeScript"] = 2] = "TypeScript";
Courses[Courses["Ionic"] = 3] = "Ionic";
Courses[Courses["Angular2"] = 4] = "Angular2";
Courses[Courses["NodeJS"] = 5] = "NodeJS";
})(Courses || (Courses = {}));
;
var tscourse = Courses.TypeScript;
console.log(tscourse); //2
An enum type can be assigned to the Number primitive type, and vice versa.
enum.ts
enum.js
var Courses;
(function (Courses) {
Courses[Courses["TypeScript"] = 2] = "TypeScript";
Courses[Courses["Ionic"] = 3] = "Ionic";
Courses[Courses["Angular2"] = 4] = "Angular2";
Courses[Courses["NodeJS"] = 5] = "NodeJS";
})(Courses || (Courses = {}));
;
var tscourse = Courses.Ionic;
var c = tscourse;
Object Types
The primitive types in TypeScript are the Array, Tuple, Function, Class and Interface.
Array
The Array type is used to store same type of multiple values in a single variable and further your array
elements you can access using the index number.
An Array type can be defined using square brackets '[ ]' followed by elemType or generic array type
'Array<elemType>' as given below:
array.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
array.js
Tuple
The Tuple type represents a JavaScript array where you can define the datatype of each element in array.
31
tuple.ts
Page
let tuple: [string, number];
tuple = ["Gurukulsight", 1];
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
tuple.js
var tuple;
tuple = ["Gurukulsight", 1];
Function
Like JavaScript, TypeScript functions can be created both as a named function or as an anonymous
function. In TypeScript, you can add types to each of the parameter and also add a return type to
function.
function.ts
function.js
function add(x, y) {
return x + y;
}
var sum = function (x, y) {
return x + y;
};
Class
ECMAScript 6 or ES6 provides class type to build JavaScript application by using object-oriented class-
based approach. In TypeScript, you can compile class type down to JavaScript standard ES5 that will work
across all major browsers and platforms.
32
Page
class.ts
class Student {
rollNo: number;
name: string;
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
class.js
Interface
Interface acts as a contract between itself and any class which implements it. Interface cannot be
instantiated but it can be referenced by the class object which implements it.
Hence, it can be used to represent any non-primitive JavaScript object.
interface.ts
interface IHuman {
firstName: string;
lastName: string;
}
class Employee implements IHuman {
constructor(public firstName: string, public lastName: string) {
33
}
}
Page
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
interface.js
Template Strings
JavaScript uses double quotes (") or single quotes (') to surround string data. String data within double
or single quotes can only be in one line and there is no way to insert data into these strings. This results
into a lot of string concatenation.
strings
//string concatenation
let str = 'Hello, my name is ' + firstname + ' and I am the founder of ' + site;
console.log(str);
To solve these issues ES6 introduces a new type of string literal that is marked with back ticks (`). By using
back ticks (`) you can manipulate strings easily.
template_strings
//template string
let str = `Hello, my name is ${firstname}
and I am the founder of ${site}`;
console.log(str);
Type Annotation
34
Type Annotations means defining the type of a variable explicitly. The type used to specify an annotation
can be a primitive type, an object type or any complex structure to represent data.
Page
type_annotation.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
type_annotation.js
var num = 2;
var str = "Gurukulsight";
var numberList = [1, 2, 3];
Type Inference
Type inference is a mechanism to determine the type of data at compile time in the absence of explicit
type annotations. TypeScript will infer the type from the initial value.
type_inference.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
type_inference.js
anglebracket.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
anglebracket.js
2. As syntax
anglebracket.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
anglebracket.js
Variable Statement
In TypeScript, a variable statement is extended to include optional type annotations.
Syntax
variable.js
var x = 4;
let number = 50;
const key = 'xyz123';
//OR
var x: number = 4;
37
block.js
//if block
if (flag) {
// 'a' exists here
let b = a + 1;
return b;
}
// Error: 'b' doesn't exist here
return b;
}
Hoisting
When you use var to declare a variable, you have to deal with hoisting. Hoisting is JavaScript's default
behavior of moving variable declarations to the top of the current scope (i.e. top of the current js file or
the current function). It means, in JavaScript a variable can be used before it has been declared.
hoisting.js
var x = "Gurukulsight";
function foo() {
console.log(x); //Gurukulsight
}
function bar() {
console.log(x); //undefined
var x; //x declaration is hoisted, that’s why x is undefined
}
foo();
bar();
In above bar function declaration of x variable will move to the top of bar function variable declaration
and within bar function, we have not specified any value to x, hence it’s default value is undefined.
38
Page
Important Information
JavaScript only hoists variable declarations, not variable initializations.
To avoid issues because of hoisting, always declare all variables at the beginning of every scope.
Use ES6 - let and const to avoid hoisting.
hoistingfixed.js
var x = "Gurukulsight";
function bar() {
console.log(x); //Error: x is not defined
let x; //x declaration is not hoisted
}
bar();
Destructuring
Destructuring means breaking up the structure. Destructuring is a way to quickly extract the data from a single
object or array and assign it to multiple variables within a single statement. ES6 also supports object destructuring.
1. Object Destructuring
2. Array Destructuring
destructuring.ts
console.log(x); // 'one'
console.log(y); // 'two'
console.log(z); // 'three'
console.log(x); // 'one'
console.log(y); // 'two'
console.log(z); // 'three'
39
Destructuring can also be used for passing objects into a function which allow you to extract specific properties
from an object.
Page
destructuring_auguments.ts
statements.ts
if (true) {
console.log("if statement");
}
let i: number = 1;
do {
console.log("do..while loop");
i++;
} while (i <= 1);
let j: number = 1;
while (j <= 1) {
console.log("while loop");
j++;
}
For..In Statement
The for...in loop iterates over the properties of an iterable object i.e. list type. The for...in loop returns
a list of keys on the object being iterated and using the keys on that object you can access values.
40
forin.ts
Page
let list: number = [4, 5, 6];
For..Of Statement
The for...of loop iterates over the properties of an iterable object i.e. list type. The for...of loop returns
a list of values on the object being iterated.
forin.ts
Operators
TypeScript supports all of the standard JavaScript operators like arithmetic operators, comparison
operators, assignment operators, conditional operators, bitwise operators, logical operators and Type
Operators.
41
Page
Functions
Introduction
TypeScript extends JavaScript functions with typed parameters, return type annotations, overloads,
default parameter values, and rest parameters. Like JavaScript, TypeScript functions can be created both
as a named function or as an anonymous function.
function.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
function.js
function add(x, y) {
return x + y;
}
var sum = function (x, y) {
return x + y;
};
Optional Parameters
In JavaScript, you can call a function without passing any arguments, even the function specifies
parameters. Hence every parameter in JavaScript function is optional and when you do this, each
parameter value is undefined.
In TypeScript, functions parameters are not optional. The compiler checks each call and warns you if you
are not passing the values as per the function receiving parameters type.
42
TypeScript supports optional parameter by suffixing question mark '? ' to the parameter. Also, optional
Page
parameter you can add after any required parameters in the parameter list.
optionalparameter.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
optionalparameter.js
function add(x, y, z) {
if (z !== undefined)
return x + y + z;
else
return x + y;
}
var resul1 = add(2, 3); //5
var resul2 = add(2, 3, 5); //10
Default Parameters
In TypeScript, you can set a default value to a function parameter and when user does not pass the value
for that parameter, default value will be used for that parameter. Also, default parameter you can add
after any required parameters in the parameter list.
defaultparameter.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
43
defaultparameter.js
Page
function add(x, y, z) {
if (z === void 0) { z = 0; }
return x + y + z;
}
var resul1 = add(2, 3); //5
var resul2 = add(2, 3, 5); //10
Rest Parameters
The Rest parameter allow you to pass zero or more values to a function. A Rest parameter is prefixed by
three consecutive dot characters '…' and allow the functions to have a variable number of arguments
without using the arguments object. The rest parameter is an instance of Array, so all array methods
work.
A rest parameter must follow following three rules:
restparameter.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
restparameter.js
function add(x) {
var y = [];
for (var _i = 1; _i < arguments.length; _i++) {
y[_i - 1] = arguments[_i];
}
var result = x;
44
Spread Operator
The spread operator is introduced with ES6. It allows you to expand an array into multiple formal
parameters. In ES6, the spread operator example is given below:
spreadoperator_es6.js
function add(x, y, z) {
return x + y + z;
}
In TypeScript, the spread operator acts like a reverse of rest parameter. The spread operator in
TypeScript you can use with rest parameter as given below:
spreadoperator.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
spreadoperator.js
function add() {
var x = [];
for (var _i = 0; _i < arguments.length; _i++) {
45
x[_i - 0] = arguments[_i];
}
Page
var result = 0;
for (var i = 0; i < x.length; i++) {
result += x[i];
}
return result;
}
var nums = [2, 5, 5];
var result = add.apply(void 0, nums); //12
Function Overloads
In TypeScript, Function overloads is purely a compile-time process. It has no impact on the compiled
JavaScript code.
The parameter list of a function overload cannot have default parameters. But you can define optional
parameter using question mark '? ' in function overloads.
functionoverloads.ts
// implementation signature
function add(x: any, y: any, z: any): any {
let result: any;
if (typeof x == "number" && typeof y == "number" && typeof z == "number") {
result = x + y + z;
}
else {
result = x + y + " " + z;
}
return result;
}
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
functionoverloads.js
function add(x, y, z) {
var result;
if (typeof x == "number" && typeof y == "number" && typeof z == "number") {
46
result = x + y + z;
}
Page
else {
result = x + y + " " + z;
}
return result;
}
var result1 = add(4, 3, 8); // 15
var result2 = add("Gurukul", "sight", "website"); //Gurukulsight website
Arrow Function
ES6 provides shorthand syntax for defining anonymous function. Arrow function omit the function
keyword and have lexical scoping of this keyword. TypeScript extends arrow function with types
parameters.
arrowfunction.ts
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
arrowfunction.js
The arrow function is typically useful for writing callbacks, which often have an undefined or unexpected
this. The use of an arrow function causes the callback to have the same this as the surrounding method
have. Let’s understand the concept with the following example.
arrowcallback.ts
class Messenger {
message: string = "Hello Gurukulsight!";
greetArrow(): void {
//arrow function as a callback
47
greetAnonymous(): void {
//anonymous function as a callback
setTimeout(function () {
console.log(this.message); // doesn’t contain parent scope
}, 3000);
}
};
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
arrowcallback.js
48
Page
Classes
Introduction
ECMAScript 6 or ES6 provides class type to build JavaScript application by using object-oriented class-
based approach. TypeScript extends ES6 class type with typed members and access modifiers like classes
in C# or Java programming languages.
In TypeScript, you can compile class type down to JavaScript standard ES5 that will work across all major
browsers and platforms.
class.ts
class Student {
private rollNo: number;
private name: string;
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
class.js
}
Student.prototype.showDetails = function () {
Page
console.log(this.rollNo + " : " + this.name);
};
return Student;
}());
var s1 = new Student(1, "Shailendra Chauhan");
s1.showDetails();
Constructors
Just like object oriented programming languages C# or Java, TypeScript class type supports two types of
constructors - default constructor and parameterized constructor.
Unlike C# or Java, in typescript constructor, you can make public, private or protected instance members
of a class.
constructor.ts
class Customer {
//instance members with access modifiers
constructor(private id:number, public name:string, protected address:string) { }
showDetails() {
console.log(this.id + " : " + this.name + " : " + this.address);
}
}
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
constructor.js
};
return Customer;
Page
}());
var c1 = new Customer(1, "Shailendra Chauhan", "Noida");
c1.showDetails();
members.ts
class Booklist {
//instance members
private books: string[] = []; //instance property or instance member
constructor(public name: string) {
}
addBook(book: string) { //member function or instance member function
if (this.books.length >= Booklist.maxBookCount) {
throw new Error('Booklist is full');
}
else {
this.books.push(book);
Booklist.totalBooksCount++;
}
}
//static members
static totalBooksCount: number = 0;
static maxBookCount: number = 20;
static totalBooks() { //static methods
return Booklist.totalBooksCount;
}
}
console.log(maxBooks);
console.log(totalBooks);
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
members.js
Booklist.totalBooksCount = 0;
Booklist.maxBookCount = 20;
var booklist = new Booklist('My Book List');
Public - By default, members (properties and methods) of TypeScript class are public - so you don’t
need to prefix members with the public keyword. Public members are accessible everywhere
without restrictions
Private - A private member cannot be accessed outside of its containing class. Private members can
be accessed only within the class.
Protected - A protected member cannot be accessed outside of its containing class. Protected
members can be accessed only within the class and by the instance of its sub/child class.
In compiled JavaScript code, there will be no such types of restriction on the members.
accessmodifiers.ts
class Foo {
private x: number;
protected y: number;
public z: number;
saveData(foo: Foo): void {
this.x = 1; // ok
this.y = 1; // ok
this.z = 1; // ok
foo.x = 1; // ok
foo.y = 1; // ok
foo.z = 1; // ok
}
}
bar.y = 1; // ok
bar.z = 1; // ok
foo.z = 1; // ok
}
Page
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
accessmodifiers.js
Readonly Modifiers
TypeScript supports readonly modifiers on property level by using the readonly keyword. The Readonly
properties must be initialized at their declaration or in the constructor.
readonly.ts
class Company {
readonly country: string = "India";
readonly name: string;
54
constructor(_name: string) {
Page
this.name = _name;
}
showDetails() {
console.log(this.name + " : " + this.country);
}
}
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
readonly.js
Accessors
Just like C# properties accessors, TypeScript supports get/set accessors to access and to set the value to
a member of an object. This way give us control over how a member of an object is accessed and set.
accessors.ts
class Employee {
private passcode: string;
private _fullName: string;
constructor(_passcode?: string) {
this.passcode = _passcode;
}
55
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
accessors.js
return Employee;
Page
}());
var e1 = new Employee("secret_passcode");
e1.fullName = "Shailendra Chauhan";
if (e1.fullName) {
console.log(e1.fullName);
}
var e2 = new Employee();
e2.fullName = "Kanishk Puri"; //Error: Unauthorized update of employee
if (e2.fullName) {
console.log(e1.fullName);
}
Inheritance
Inheritance is an important aspect of object oriented programming languages like C# and Java.
Inheritance is a mechanism of acquiring the features and behaviors of a class by another class. The class
whose members are inherited is called the base class, and the class that inherits those members is called
the derived/child class. Further, in child class you can override or modify the behaviors of its parent class
and also can add new one.
Traditional JavaScript uses functions and prototype-based inheritance but TypeScript supports object-
oriented class-based inheritance. Hence, in TypeScript you can extend the features and behaviors of an
existing class into new one through the extends keyword.
Like C# and Java languages, TypeScript supports only single inheritance and multi-level inheritance. It
doesn’t support multiple and hybrid inheritance.
inheritance.ts
class Person {
private firstName: string;
private lastName: string;
constructor(_firstName: string, _lastName: string) {
this.firstName = _firstName;
this.lastName = _lastName;
}
fullName(): string {
return this.firstName + " " + this.lastName;
}
}
super(_firstName, _lastName);
Page
this.id = _id;
}
showDetails(): void {
//calling parent class method
console.log(this.id + " : " + this.fullName());
}
}
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
inheritance.js
abstract.ts
abstract.js
s.Area();
Page
Interfaces
Introduction
Interface acts as a contract between itself and any class which implements it. It means a class that
implement an interface is bound to implement all its members. Interface cannot be instantiated but it
can be referenced by the class object which implements it. Interfaces can be used to represent any non-
primitive JavaScript object.
interface.ts
interface IHuman {
firstName: string;
lastName: string;
}
class Employee implements IHuman {
constructor(public firstName: string, public lastName: string) {
}
}
The compiled JavaScript (ES5) code for the above TypeScript code is give below:
interface.js
Use of Interfaces
Interfaces are particularly useful for validating the required structure of properties, objects passed as
parameters, and objects returned from functions.
61
Also, Interfaces are only TypeScript compile-time construct and compiled JavaScript code have no such
representation.
Page
Interface Inheritance
An interface can be inherited from zero or more base types. The base type can be a class or interface.
Let’s understand the interface inheritance with the following examples:
Interface1.ts
interface IStore {
Read(): void;
Write(): void;
}
interface ICompress {
Compress(): void;
Decompress(): void;
}
Interface2.ts
interface IStore {
Read(): void;
Write(): void;
}
interface ICompress {
Compress(): void;
Decompress(): void;
}
Interface.ts
class Store {
Read(): void {
console.log("Read Method for Store");
}
Write(): void {
console.log("Write Method for Store");
}
}
I1.Read();
Page
I1.Write();
Generics
Introduction
Generics enforce type safety without compromising performance, or productivity. In generics, a type
parameter is supplied between the open (<) and close (>) brackets and which makes it strongly typed
collections i.e. generics collections contain only similar types of objects.
In TypeScript, you can create generic functions, generic methods, generic interfaces and generic classes.
generic.ts
Generic Functions
When a function implementation includes type parameters in its signature then it is called a generic
function. A generic function has a type parameter enclosed in angle brackets (< >) immediately after the
function name.
The following is an example of generic function:
genericfunction.ts
revList.push(list[i]);
}
Page
return revList;
}
let letters = ['a', 'b', 'c', 'd', 'e'];
let reversedLetters = doReverse<string>(letters); // e, d, c, b, a
Generics are purely compile-time representation; compiled JavaScript code does not have such
representation. The compiled JavaScript (ES5) code for the above TypeScript code is give below:
genericfunction.js
function doReverse(list) {
var revList = [];
for (var i = (list.length - 1); i >= 0; i--) {
revList.push(list[i]);
}
return revList;
}
var letters = ['a', 'b', 'c', 'd', 'e'];
var reversedLetters = doReverse(letters);
Generic Classes
A generic class has a type parameter enclosed in angle brackets (< >) immediately after the class name.
In generic class, same type parameter can be used to annotate method parameters, properties, return
types, and local variables.
The following is an example of generic class:
genericclass.ts
class ItemList<T>
{
private itemArray: Array<T>;
constructor() {
this.itemArray = [];
}
Add(item: T) : void {
65
this.itemArray.push(item);
Page
}
GetAll(): Array<T> {
return this.itemArray;
}
}
let fruits = new ItemList<string>();
fruits.Add("Apple");
fruits.Add("Mango");
fruits.Add("Orange");
Generics are purely compile-time representation; compiled JavaScript code does not have such
representation. The compiled JavaScript (ES5) code for the above TypeScript code is give below:
genericclass.js
genericinterface.ts
interface IItemList<T> {
itemArray: Array<T>;
Add(item: T): void;
GetAll(): Array<T>;
}
genericinterface.js
68
Page
Modules and Namespaces
Introduction
A module is a container to a group of related variables, functions, classes, and interfaces etc. Variables,
functions, classes, and interfaces etc. declared in a module are not accessible outside the module unless
they are explicitly exported using export keyword. Also, to consume the members of a module, you have
to import it using import keyword.
Modules are declarative and the relationship between modules is specified in terms of imports and
exports at the file level. Modules are also available in ES6/ECMAScript 2015.
Important Information
From TypeScript 1.5, "Internal modules" are "namespaces" and "External modules" are simply
"modules" to match ES6 module terminology
Export
In TypeScript, you can export any declaration such as a variable, function, class, type alias, or interface
by using export keyword.
myModule.ts
}
Page
Import
In TypeScript, you can import an exported declaration by using import keyword. Let’s import the
myModule file types within app file as given below:
app.ts
//importing the exporting types Student and Employee from myModule file
import { Student, Employee } from "./myModule";
Re-Export
In TypeScript, sometimes modules extend other modules, and partially expose some of their features. In
this case, you can re-export some of their features either using their original name or introducing a new
name. Let’s re-export the myModule file only Student type as show below:
re_export.ts
Now, you can import the types form re_export file as given below:
app.ts
namespace.ts
namespace Gurukulsight {
//exporting outside the namespace body
export class Student {
constructor(private rollNo: number, private name: string) { }
showDetails() {
return this.rollNo + ", " + this.name;
}
}
// Only available inside the namespace body
let maxCount: number = 100;
class Employee {
constructor(private firstName: string, private lastName: string) { }
showDetails() {
return this.firstName + ", " + this.lastName;
}
}
}
namespace DotNetTricks {
//accessing Gurukulsight namespace student class
import Student = Gurukulsight.Student;
Important Information
A namespace can be described in multiple files and allow to keep each file to a maintainable size.
The members of a module body, you can access only within that module body.
71
To make a member available outside the namespace body, you need to prefix the member with
Page
gurukulsight.ts
main.ts
Class Decorator
A Class Decorator is attached to a class declaration and tell about the class behaviors. The class decorator
is applied to the constructor of the class and can be used to observe, modify, or replace a class definition.
classdecorator.ts
@sealed
class Employee {
constructor(private firstName: string, private lastName: string) { }
showDetails() {
return this.firstName + ", " + this.lastName;
}
}
In above example, @sealed decorator will seal both the constructor and its prototype so that you cannot
inherit the class.
Method Decorator
73
Page
class ItemList {
itemArray: Array<string>;
constructor() {
this.itemArray = [];
}
@log
Add(item: string): void {
this.itemArray.push(item);
}
GetAll(): Array<string> {
return this.itemArray;
}
}
In above example, @log decorator will log the new item entry.
Property Decorator
A property Decorator is attached to the properties of a class.
propertydecorator.ts
class Company {
@ReadOnly
name: string = "Dot Net Tricks";
}
In above example, @ReadOnly decorator will make the name property as readonly, so you can’t change
its value.
Important Information
This book has been written by referring to official website of TypeScript at www.typescriptlang.org.
74
Page
Other Free E-Books
The author will truly appreciate it, if you will share his additional books among others because he wants it to reach
as many techy people as possible so that they can also get benefited by his contribution.
You can download these books from www.dotnettricks.com in PDF format absolutely free.
75
Page
Page
76