Typescript Tutorial
Typescript Tutorial
TypeScript is pure object oriented with classes, interfaces and statically typed like C# or
Java. The popular JavaScript framework Angular 2.0 is written in TypeScript. Mastering
TypeScript can help programmers to write object-oriented programs and have them
compiled to JavaScript, both on server side and client side.
Audience
Programmers coming from Object Oriented world will find it easy to use TypeScript. With
the knowledge of TypeScript, they can build web applications much faster, as TypeScript
has good tooling support.
Prerequisites
As a reader of this tutorial, you should have a good understanding of OOP concepts and
basic JavaScript, to make the most of this tutorial.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
TypeScript
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
1. TYPESCRIPT OVERVIEW..................................................................................................... 1
What is TypeScript?................................................................................................................................. 1
Features of TypeScript............................................................................................................................. 1
Installing Node.js..................................................................................................................................... 5
Brackets ................................................................................................................................................ 11
ii
TypeScript
6. TYPESCRIPT OPERATORS................................................................................................. 28
Assignment Operators........................................................................................................................... 36
The if Statement.................................................................................................................................... 42
iii
TypeScript
Syntactic Variations............................................................................................................................... 77
toExponential() ..................................................................................................................................... 85
toFixed() ................................................................................................................................................ 86
iv
TypeScript
toLocaleString() ..................................................................................................................................... 87
toPrecision() .......................................................................................................................................... 87
toString() ............................................................................................................................................... 88
valueOf() ............................................................................................................................................... 89
charAt ................................................................................................................................................... 93
charCodeAt() ......................................................................................................................................... 94
concat() ................................................................................................................................................. 95
indexOf() ............................................................................................................................................... 95
lastIndexOf() ......................................................................................................................................... 96
localeCompare() .................................................................................................................................... 97
replace() ................................................................................................................................................ 98
search() ................................................................................................................................................. 99
substr()................................................................................................................................................ 101
v
TypeScript
every()................................................................................................................................................. 112
reduce()............................................................................................................................................... 120
vi
TypeScript
vii
TypeScript
viii
1. TypeScript Overview TypeScript
JavaScript was introduced as a language for the client side. The development of Node.js
has marked JavaScript as an emerging server-side technology too. However, as JavaScript
code grows, it tends to get messier, making it difficult to maintain and reuse the code.
Moreover, its failure to embrace the features of Object Orientation, strong type checking
and compile-time error checks prevents JavaScript from succeeding at the enterprise level
as a full-fledged server-side technology. TypeScript was presented to bridge this gap.
What is TypeScript?
By definition, TypeScript is JavaScript for application-scale development.
Features of TypeScript
TypeScript is just JavaScript. TypeScript starts with JavaScript and ends with
JavaScript. Typescript adopts the basic building blocks of your program from JavaScript.
Hence, you only need to know JavaScript to use TypeScript. All TypeScript code is
converted into its JavaScript equivalent for the purpose of execution.
JavaScript is TypeScript. This means that any valid .js file can be renamed to .ts and
compiled with other TypeScript files.
1
TypeScript
Additional
ECMASCRIPT5 ECMASCRIPT6 TypeScript
Features
TypeScript adopts its basic language features from the ECMAScript5 specification, i.e., the
official specification for JavaScript. TypeScript language features like Modules and class-
based orientation are in line with the EcmaScript 6 specification. Additionally, TypeScript
also embraces features like generics and type annotations that arent a part of the
EcmaScript6 specification.
Strong Static Typing: JavaScript is not strongly typed. TypeScript comes with an
optional static typing and type inference system through the TLS (TypeScript
Language Service). The type of a variable, declared with no type, may be inferred
by the TLS based on its value.
2
TypeScript
Components of TypeScript
At its heart, TypeScript has the following three components:
The TypeScript Compiler: The TypeScript compiler (tsc) converts the instructions
written in TypeScript to its JavaScript equivalent.
Declaration Files
When a TypeScript script gets compiled, there is an option to generate a declaration file
(with the extension .d.ts) that functions as an interface to the components in the compiled
JavaScript. The concept of declaration files is analogous to the concept of header files
found in C/C++. The declaration files (files with .d.ts extension) provide intellisense for
types, function calls, and variable support for JavaScript libraries like jQuery, MooTools,
etc.
3
2. TypeScript Environment Setup TypeScript
In this chapter, we will discuss how to install TypeScript on Windows platform. We will also
explain how to install the Brackets IDE.
var num:number=12
console.log(num)
12
4
TypeScript
A Text Editor
The text editor helps you to write your source code. Examples of a few editors include
Windows Notepad, Notepad++, Emacs, vim or vi, etc. Editors used may vary with
Operating Systems.
The source files are typically named with the extension .ts
The TSC generates a JavaScript version of the .ts file passed to it. In other words, the TSC
produces an equivalent JavaScript source code from the Typescript file given as an input
to it. This process is termed as transpilation.
However, the compiler rejects any raw JavaScript file passed to it. The compiler deals with
only .ts or .d.ts files.
Installing Node.js
Node.js is an open source, cross-platform runtime environment for server-side JavaScript.
Node.js is required to run JavaScript without a browser support. It uses Google V8
JavaScript engine to execute code. You may download Node.js source code or a pre-built
installer for your platform. Node is available here: https://nodejs.org/en/download
Installation on Windows
Follow the steps given below to install Node.js in Windows environment.
5
TypeScript
Step 2: To verify if the installation was successful, enter the command node v in the
terminal window.
Step 3: Type the following command in the terminal window to install TypeScript.
Installation on Mac OS X
To install node.js on Mac OS X, you can download a pre-compiled binary package which
makes a nice and easy installation. Head over to http://nodejs.org/ and click the install
button to download the latest package.
6
TypeScript
Install the package from the .dmg by following the install wizard which will install both
node and npm. npm is Node Package Manager which facilitates installation of additional
packages for node.js.
7
TypeScript
Installation on Linux
You need to install a number of dependencies before you can install Node.js and NPM.
Ruby and GCC. Youll need Ruby 1.8.6 or newer and GCC 4.2 or newer.
Homebrew. Homebrew is a package manager originally designed for Mac, but its
been ported to Linux as Linuxbrew. You can learn more about Homebrew at
http://brew.sh and Linuxbrew at http://brew.sh/linuxbrew.
Once these dependencies are installed, you may install Node.js by using the following
command on the terminal:
IDE Support
Typescript can be built on a plethora of development environments like Visual Studio,
Sublime Text 2, WebStorm/PHPStorm, Eclipse, Brackets, etc. Visual Studio Code and
Brackets IDEs are discussed here. The development environment used here is Visual
Studio Code (Windows platform).
Installation on Windows
Step 1: Download Visual Studio Code for Windows.
8
TypeScript
9
TypeScript
Step 4: You may directly traverse to the files path by right clicking on the file open in
command prompt. Similarly, the Reveal in Explorer option shows the file in the File
Explorer.
10
TypeScript
Installation on Mac OS X
Visual Studio Codes Mac OS X specific installation guide can be found at
https://code.visualstudio.com/Docs/editor/setup
Installation on Linux
Linux specific installation guide for Visual Studio Code can be found at
https://code.visualstudio.com/Docs/editor/setup
Brackets
Brackets is a free open-source editor for web development, created by Adobe Systems. It
is available for Linux, Windows and Mac OS X. Brackets is available at http://brackets.io
11
TypeScript
Post installation, click on the extension manager icon on the right-hand side
of the editor. Enter typescript in the search box.
You can run DOS prompt / shell within Brackets itself by adding one more extension
Brackets Shell.
12
TypeScript
Upon installation, you will find an icon of shell on the right-hand side of the editor .
Once you click on the icon, you will see the shell window as shown below:
Note: Typescript is also available as a plugin for Visual Studio 2012 and 2013
environments (http://www.typescriptlang.org/#Download).VS 2015 and above includes
Typescript plugin by default.
13
3. TypeScript Basic Syntax TypeScript
Syntax defines a set of rules for writing programs. Every language specification defines its
own syntax. A TypeScript program is composed of:
Modules
Functions
Variables
Statements and Expressions
Comments
Line 2 prints the variables value to the prompt. Here, console refers to the terminal
window. The function log () is used to display text on the screen.
Step 1: Save the file with .ts extension. We shall save the file as Test.ts. The code editor
marks errors in the code, if any, while you save it.
Step 2: Right-click the TypeScript file under the Working Files option in VS Codes Explore
Pane. Select Open in Command Prompt option.
14
TypeScript
Step 3: To compile the file use the following command on the terminal window:
tsc Test.ts
Step 4: The file is compiled to Test.js. To run the program written, type the following in
the terminal:
node Test.js
Compiler Flags
Compiler flags enable you to change the behavior of the compiler during compilation. Each
compiler flag exposes a setting that allows you to change how the compiler behaves.
The following table lists some common flags associated with the TSC compiler. A typical
command-line usage uses some or all switches.
15
TypeScript
Identifiers in TypeScript
Identifiers are names given to elements in a program like variables, functions etc. The
rules for identifiers are:
Identifiers can include both, characters and digits. However, the identifier cannot
begin with a digit.
Identifiers cannot include special symbols except for underscore (_) or a dollar
sign ($).
The following tables lists a few examples of valid and invalid identifiers:
firstName var
first_name first name
num1 first-name
$result 1number
TypeScript Keywords
Keywords have a special meaning in the context of a language. The following table lists
some keywords in TypeScript.
16
TypeScript
TypeScript is Case-sensitive
TypeScript is case-sensitive. This means that TypeScript differentiates between uppercase
and lowercase characters.
Example
console.log("hello world")
console.log("We are learning TypeScript")
A single line can contain multiple statements. However, these statements must be
separated by a semicolon.
Comments in TypeScript
Comments are a way to improve the readability of a program. Comments can be used to
include additional information about a program like author of the code, hints about a
function/ construct etc. Comments are ignored by the compiler.
Multi-line comments (/* */) : These comments may span multiple lines.
Example
//this is single line comment
/* This is a
Multi-line comment
17
TypeScript
*/
The above example defines a class Greeting. The class has a method greet (). The method
prints the string Hello World on the terminal. The new keyword creates an object of the
class (obj). The object invokes the method greet ().
18
TypeScript
Hello World!!!
19
4. TypeScript Types TypeScript
The Type System represents the different types of values supported by the language. The
Type System checks the validity of the supplied values, before they are stored or
manipulated by the program. This ensures that the code behaves as expected. The Type
System further allows for richer code hinting and automated documentation too.
TypeScript provides data types as a part of its optional Type System. The data type
classification is as given below:
Built-in types
The following table illustrates all the built-in types in TypeScript:
Data
Keyword Description
type
Number number Double precision 64-bit floating point values. It can be used
to represent both, integers and fractions.
20
TypeScript
However, null and undefined are not the same. A variable initialized with undefined means
that the variable has no value or object assigned to it while null means that the variable
has been set to an object whose value is undefined.
User-defined Types
User-defined types include Enumerations (enums), classes, interfaces, arrays, and tuple.
These are discussed in detail in the later chapters.
21
5. TypeScript Variables TypeScript
A variable, by definition, is a named space in the memory that stores values. In other
words, it acts as a container for values in a program. TypeScript variables must follow the
JavaScript naming rules:
They cannot contain spaces and special characters, except the underscore (_) and
the dollar ($) sign.
A variable must be declared before it is used. Use the var keyword to declare variables.
22
TypeScript
The following table illustrates the valid syntax for variable declaration as discussed above:
var name=mary The variables type is inferred from the data type of
the value. Here, the variable is of the type string
var name; The variables data type is any. Its value is set to
undefined by default.
23
TypeScript
name:John
first score:50
second score:42.50
sum of the scores:92.50
The TypeScript compiler will generate errors, if we attempt to assign a value to a variable
that is not of the same type. Hence, TypeScript follows Strong Typing. The Strong typing
syntax ensures that the types specified on either side of the assignment operator (=) are
the same. This is why the following code will result in a compilation error:
Example
var str='1'
var str2:number=<number> <any> str //str is now of type number
console.log(str2)
If you hover the mouse pointer over the type assertion statement in Visual Studio Code,
it displays the change in the variables data type. Basically it allows the assertion from
type S to T succeed if either S is a subtype of T or T is a subtype of S.
The reason why it's not called "type casting" is that casting generally implies some sort of
runtime support while, type assertions are purely a compile time construct and a way
for you to provide hints to the compiler on how you want your code to be analyzed.
24
TypeScript
The code declares a variable and sets its value to 2. Note that the variable
declaration doesnt specify the data type. Hence, the program uses inferred typing
to determine the data type of the variable, i.e., it assigns the type of the first value
that the variable is set to. In this case, num is set to the type number
When the code tries to set the variables value to string. The compiler throws an
error as the variables type is already set to number.
Global Scope Global variables are declared outside the programming constructs.
These variables can be accessed from anywhere within your code.
Class Scope These variables are also called fields. Fields or class variables are
declared within the class but outside the methods. These variables can be accessed
using the object of the class. Fields can also be static. Static fields can be accessed
using the class name.
Local Scope Local variables, as the name suggests, are declared within the
constructs like methods, loops etc. Local variables are accessible only within the
construct where they are declared.
25
TypeScript
26
TypeScript
Global num: 12
10
Global num: 13
If you try accessing the local variable outside the method, it results in a compilation error.
27
6. TypeScript Operators TypeScript
What is an Operator?
An operator defines some function that will be performed on the data. The data on which
operators work are called operands. Consider the following expression:
7 + 5 = 12
Here, the values 7, 5, and 12 are operands, while + and = are operators.
Arithmetic operators
Logical operators
Relational operators
Bitwise operators
Assignment operators
Ternary/conditional operator
String operator
Type Operator
Arithmetic Operators
Assume the values in variables a and b are 10 and 5 respectively.
Example
Operator Function
28
TypeScript
29
TypeScript
Sum: 12
Difference: 8
Product: 20
Quotient : 5
Remainder: 0
Value of num1 after increment: 11
Value of num2 after decrement: 1
Relational Operators
Relational Operators test or define the kind of relationship between two entities. Relational
operators return a Boolean value, i.e., true/ false.
Example
var num1:number=5;
var num2:number=9;
console.log("Value of num1: "+num1);
console.log("Value of num2 :"+num2);
var res=num1>num2
console.log("num1 greater than num2: "+res)
30
TypeScript
res=num1<num2
console.log("num1 lesser than num2: "+res)
res=num1>=num2
console.log("num1 greater than or equal to num2: "+res)
res=num1<=num2
console.log("num1 lesser than or equal to num2: "+res)
res=num1==num2
console.log("num1 is equal to num2: "+res)
res=num1!=num2
console.log("num1 is not equal to num2: "+res)
var num1 = 5;
var num2 = 9;
console.log("Value of num1: " + num1);
console.log("Value of num2 :" + num2);
var res = num1 > num2;
console.log("num1 greater than num2: " + res);
res = num1 < num2;
console.log("num1 lesser than num2: " + res);
res = num1 >= num2;
console.log("num1 greater than or equal to num2: " + res);
res = num1 <= num2;
console.log("num1 lesser than or equal to num2: " + res);
res = num1 == num2;
console.log("num1 is equal to num2: " + res);
res = num1 != num2;
console.log("num1 not equal to num2: " + res);
31
TypeScript
Value of num1: 5
Value of num2 :9
num1 greater than num2: false
num1 lesser than num2: true
num1 greater than or equal to num2: false
num1 lesser than or equal to num2: true
14 num1 is equal to num2: false
16 num1 not equal to num2: true
Logical Operators
Logical Operators are used to combine two or more conditions. Logical operators too return
a Boolean value. Assume the value of variable A is 10 and B is 20
Example
var avg:number=20;
var percentage:number=90;
console.log("Value of avg: "+avg+" ,value of percentage: "+percentage);
var res:boolean=((avg>50)&&(percentage>80));
console.log("(avg>50)&&(percentage>80): ",res);
var res:boolean=((avg>50)||(percentage>80));
console.log("(avg>50)||(percentage>80): ",res);
32
TypeScript
var res:boolean=!((avg>50)&&(percentage>80));
console.log("!((avg>50)&&(percentage>80)): ",res);
var a=10
var result=( a<10 && a>5)
In the above example, a < 10 and a > 5 are two expressions combined by an && operator.
Here, the first expression returns false. However, the && operator requires both the
expressions return true. So, the operator skips the second expression.
The || operator returns true, if one of the expressions returns true. For example:
var a=10
var result=( a>5 || a<10)
In the above snippet, two expressions a > 5 and a < 10 are combined by a || operator.
Here, the first expression returns true. Since, the first expression returns true, the ||
operator skips the subsequent expression and returns true.
33
TypeScript
Due to this behavior of the && and || operator, they are called as short-circuit
operators.
Bitwise Operators
Assume variable A=2 and B =3
>>> (Right shift This operator is just like the >> operator, except (A >>> 1) is 1
with Zero) that the bits shifted in on the left are always zero.
Example
var a:number = 2; // Bit presentation 10
var b:number = 3; // Bit presentation 11
var result;
result = (a & b);
console.log("(a & b) => ",result)
result = (a | b);
console.log("(a | b) => ",result)
result = (a ^ b);
34
TypeScript
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
35
TypeScript
Assignment Operators
Assigns values from the right side operand to the left side operand
= (Simple
Assignment)
Ex: C = A + B will assign the value of A + B into C
It adds the right operand to the left operand and assigns the result to the
+= (Add
left operand.
and
Assignment)
Ex: C += A is equivalent to C = C + A
It subtracts the right operand from the left operand and assigns the result
-= (Subtract
to the left operand.
and
Assignment)
Ex: C -= A is equivalent to C = C - A
It multiplies the right operand with the left operand and assigns the result
*= (Multiply
to the left operand.
and
Assignment)
Ex: C *= A is equivalent to C = C * A
/= (Divide
It divides the left operand with the right operand and assigns the result
and
to the left operand.
Assignment)
Note: Same logic applies to Bitwise operators, so they will become <<=, >>=, >>=, &=,
|= and ^=.
Example
var a: number=12
var b:number=10
a=b
console.log("a=b: "+a)
a+=b
console.log("a+=b: "+a)
a-=b
console.log("a-=b: "+a)
36
TypeScript
a*=b
console.log("a*=b: "+a)
a/=b
console.log("a/=b: "+a)
a%=b
console.log("a%=b: "+a)
var a = 12;
var b = 10;
a = b;
console.log("a=b: " + a);
a += b;
console.log("a+=b: " + a);
a -= b;
console.log("a-=b: " + a);
a *= b;
console.log("a*=b: " + a);
a /= b;
console.log("a/=b: " + a);
a %= b;
console.log("a%=b: " + a);
a=b: 10
a+=b: 20
a-=b: 10
a*=b: 100
a/=b: 10
a%=b: 0
37
TypeScript
Miscellaneous Operators
var x:number=4
var y=-x;
console.log("value of x: ",x); //outputs 4
console.log("value of y: ",y); //outputs -4
value of x: 4
value of y: -4
var msg:string="hello"+"world"
console.log(msg)
helloworld
38
TypeScript
The concatenation operation doesnt add a space between strings. Multiple strings can be
concatenated in a single statement.
var num:number=-2
var result= num > 0 ?"positive":"non-positive"
console.log(result)
Line 2 checks whether the value in the variable num is greater than zero. If num is set
to a value greater than zero, it returns the string positive else the string non-positive
is returned.
non-positive
Type Operators
typeof operator
It is a unary operator. This operator returns the data type of the operand. Take a look at
the following example:
var num=12
console.log(typeof num); //output: number
39
TypeScript
number
instanceof
This operator can be used to test if an object is of a specified type or not. The use of
instanceof operator is discussed in the chapter classes.
40
7. TypeScript Decision Making TypeScript
Decision-making structures require that the programmer specifies one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.
Shown below is the general form of a typical decision-making structure found in most of
the programming languages
Statement Description
elseif and nested if You can use one if or else if statement inside another if or
statements else if statement(s).
41
TypeScript
The if Statement
The ifelse construct evaluates a condition before a block of code is executed.
Syntax
if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
If the Boolean expression evaluates to true, then the block of code inside the if statement
will be executed. If the Boolean expression evaluates to false, then the first set of code
after the end of the if statement (after the closing curly brace) will be executed.
Flowchart
42
TypeScript
Example
var num:number=5
if (num > 0)
{
console.log("number is positive")
}
The above example will print number is positive as the condition specified by the if block
is true.
number is positive
Syntax
if(boolean_expression)
{
// statement(s) will execute if the Boolean expression is true
}
else
{
// statement(s) will execute if the Boolean expression is false
}
43
TypeScript
Flowchart
The if block guards the conditional expression. The block associated with the if statement
is executed if the Boolean expression evaluates to true.
The if block may be followed by an optional else statement. The instruction block
associated with the else block is executed if the expression evaluates to false.
44
TypeScript
else {
console.log("Odd");
}
The above example prints whether the value in a variable is even or odd. The if block
checks the divisibility of the value by 2 to determine the same. Here is the output of the
above code:
Even
if (boolean_expression1)
{
//statements if the expression1 evaluates to true
}
else if (boolean_expression2)
{
//statements if the expression2 evaluates to true
}
else
{
//statements if both expression1 and expression2 result to false
}
When using ifelseif and else statements, there are a few points to keep in mind.
An if can have zero or one else's and it must come after any else..if's.
An if can have zero to many else..if's and they must come before the else.
Once an else..if succeeds, none of the remaining else..if's or else's will be tested.
45
TypeScript
2 is positive
Syntax
switch(variable_expression)
{
case constant_expr1:
{
46
TypeScript
//statements;
break;
}
case constant_expr2:
{
//statements;
break;
}
default:
{
//statements;
break;
}
}
The value of the variable_expression is tested against all cases in the switch. If the variable
matches one of the cases, the corresponding code block is executed. If no case expression
matches the matches the value of the variable_expression, the code within the default
block is associated.
The data type of the variable_expression and the constant expression must match.
Unless you put a break after each block of code, execution flows into the next block.
Flowchart
47
TypeScript
Example: switchcase
var grade:string="A";
switch(grade)
{
case "A":
{
console.log("Excellent");
break;
}
case "B":
{
console.log("Good");
break;
}
48
TypeScript
case "C":
{
console.log("Fair");
break;
}
case "D":
{
console.log("Poor");
break;
}
default:
{
console.log("Invalid choice");
break;
}
}
The example verifies the value of the variable grade against the set of constants (A, B, C,
D, and E) and executes the corresponding blocks. If the value in the variable doesnt match
any of the constants mentioned above, the default block will be executed.
49
TypeScript
console.log("Fair");
break;
}
case "D":
{
console.log("Poor");
break;
}
default:
{
console.log("Invalid choice");
break;
}
}
Excellent
50
8. TypeScript Loops TypeScript
You may encounter situations, when a block of code needs to be executed several number
of times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
51
TypeScript
TypeScript provides different types of loops to handle looping requirements. The following
figure illustrates the classification of loops:
Definite Loop
A loop whose number of iterations are definite/fixed is termed as a definite loop. The for
loop is an implementation of a definite loop.
Indefinite Loop
An indefinite loop is used when the number of iterations in a loop is indeterminate or
unknown.
while loop
do while loop
Syntax
while(condition)
{
// statements if the condition is true
}
52
TypeScript
Flow Diagram
The above code snippet uses a while loop to calculate the factorial of the value in the
variable num.
53
TypeScript
}
console.log("The factorial is " + factorial);
The loop uses a count variable to keep track of the iterations. The loop initializes the
iteration by setting the value of count to its initial value. It executes the code block,
each time the value of count satisfies the termination_condtion. The step changes the
value of count after every iteration.
54
TypeScript
Flowchart
The program calculates the factorial of the number 5 and displays the same. The for loop
generates the sequence of numbers from 5 to 1, calculating the product of the numbers
in every iteration.
55
TypeScript
120
The for...in loop is used to iterate through a list or collection of values. The data type of
val here should be string or any. The syntax of the for..in loop is as given below:
var j:any;
var n:any="a b c"
for(j in n)
{
console.log(n[j])
}
56
TypeScript
a
b
c
Syntax
do
{
//statements
}while(condition)
Flowchart
57
TypeScript
Example: dowhile
var n:number=10;
do
{
console.log(n);
n--;
}while(n>=0);
58
TypeScript
10
9
8
7
6
5
4
3
2
1
0
The example initially declares a while loop. The loop is entered only if the expression
passed to while evaluates to true. In this example, the value of n is not greater than zero,
hence the expression returns false and the loop is skipped.
On the other hand, the dowhile loop executes statement once. This is because the initial
iteration does not consider the Boolean expression. However, for the subsequent iteration,
the while checks the condition and takes the control out of the loop.
59
TypeScript
do {
console.log("Entered dowhile");
} while (n > 5);
Entered dowhile
Syntax
break
Flow diagram
Example
Now, take a look at the following example code:
60
TypeScript
var i:number=1
while(i<=10)
{
if (i % 5 == 0)
{
console.log ("The first multiple of 5 between 1 and 10 is : "+i)
break //exit the loop if the first multiple is found
}
i++
} //outputs 5 and exits the loop
Syntax
continue
Flowchart
61
TypeScript
Example
An example of the continue statement is given below:
var num:number=0
var count:number=0;
for(num=0;num<=20;num++)
{
if (num % 2==0)
{
continue
}
count++
}
console.log (" The count of odd values between 0 and 20 is: "+count)
//outputs 10
The above example displays the number of even values between 0 and 20. The loop exits
the current iteration if the number is even. This is achieved using the continue statement.
62
TypeScript
63
TypeScript
while(true)
{
//statements
}
64
9. TypeScript Functions TypeScript
Functions are the building blocks of readable, maintainable, and reusable code. A function
is a set of statements to perform a specific task. Functions organize the program into
logical blocks of code. Once defined, functions may be called to access code. This makes
the code reusable. Moreover, functions make it easy to read and maintain the programs
code.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
Defining a Function
A function definition specifies what and how a specific task would be done. Before using a
function, it must be defined. Functions are defined using the function keyword. The
syntax for defining a standard function is given below:
Syntax
function function_name()
{
// function body
}
Calling a Function
A function must be called so as to execute it. This process is termed as function
invocation.
Syntax
Function_name()
65
TypeScript
Example
function test() // function definition
{
console.log("function called")
}
test() // function invocation
On compiling, it will generate JavaScript code that looks identical to the above TypeScript
code.
function called
Returning Functions
Functions may also return value along with control, back to the caller. Such functions are
called as returning functions.
Syntax
function function_name():return_type
{
//statements
return value;
}
A function can return at the most one value. In other words, there can be only one
return statement per function.
The data type of the value returned must match the return type of the function.
Example
//function defined
function greet():string //the function returns a string
{
66
TypeScript
The example declares a function greet(). The functions return type is string.
Line function returns a string value to the caller. This is achieved by the return
statement.
The function greet() returns a string , which is stored in the variable msg. This is
later displayed as output.
Hello World
67
TypeScript
Parameterized Function
Parameters are a mechanism to pass values to functions. Parameters form a part of the
functions signature. The parameter values are passed to the function during its invocation.
Unless explicitly specified, the number of values passed to a function must match the
number of parameters defined.
While calling a function, there are two ways that arguments can be passed to a function:
This method copies the actual value of an argument into the formal
Call by value parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
Positional Parameters
function func_name( param1 [:datatype], ( param2 [:datatype])
{
}
The snippet declares a function test_param with three parameters namely, n1, s1
and p1.
It is not mandatory to specify the data type of the parameter. In the absence of a
data type, the parameter is considered to be of the type any. In the above
example, the third parameter will be of the type any.
68
TypeScript
The data type of the value passed must match the type of the parameter during its
declaration. In case the data types dont match, the compiler throws an error.
123
this is a string
Optional Parameters
Optional parameters can be used when arguments need not be compulsorily passed for a
functions execution. A parameter can be marked optional by appending a question mark
to its name. The optional parameter should be set as the last argument in a function. The
syntax to declare a function with optional parameter is as given below:
69
TypeScript
The above example declares a parameterized function. Here, the third parameter,
i.e., mail_id is an optional parameter.
If an optional parameter is not passed a value during the function call, the
parameters value is set to undefined.
The function prints the value of mail_id only if the argument is passed a value.
ID:123
Name John
ID: 111
Name mary
Email Id mary@xyz.com
Rest Parameters
Rest parameters are similar to variable arguments in Java. Rest parameters dont restrict
the number of values that you can pass to a function. However, the values passed must
all be of the same type. In other words, rest parameters act as placeholders for multiple
arguments of the same type.
To declare a rest parameter, the parameter name is prefixed with three periods. Any non-
rest parameter should come before the rest parameter.
70
TypeScript
The function addNumbers() declaration, accepts a rest parameter nums. The rest
parameters data type must be set to an array. Moreover, a function can have at
the most one rest parameter.
The function is invoked twice, by passing three and six values, respectively.
The for loop iterates through the argument list, passed to the function and
calculates their sum.
71
TypeScript
sum of numbers 6
sum of numbers 50
Default Parameters
Function parameters can also be assigned values by default. However, such parameters
can also be explicitly passed values.
Syntax
function function_name(param1[:type],param2[:type]=default_value)
{
}
Note: A parameter cannot be declared optional and default at the same time.
72
TypeScript
The example declares the function, calculate_discount. The function has two
parameters- price and rate.
The program invokes the function, passing to it only the value of the parameter
price. Here, the value of rate is 0.50 (default)
The same function is invoked, but with two arguments. The default value of rate is
overwritten and is set to the value explicitly passed.
Anonymous Function
Functions that are not bound to an identifier (function name) are called as anonymous
functions. These functions are dynamically declared at runtime. Anonymous functions
can accept inputs and return outputs, just as standard functions do. An anonymous
function is usually not accessible after its initial creation.
Syntax
var res=function( [arguments] ) { ... }
hello world
73
TypeScript
var res=function(a:number,b:number)
{
return a*b;
};
console.log(res(12,2))
The anonymous function returns the product of the values passed to it. T
24
The fundamental difference between the two is that, function declarations are parsed
before their execution. On the other hand, function expressions are parsed only when the
script engine encounters it during execution.
When the JavaScript parser sees a function in the main code flow, it assumes Function
Declaration. When a function comes as a part of a statement, it is a Function Expression
Syntax
var res=new Function( [arguments] ) { ... }.
Example
74
TypeScript
The new Function() is a call to the constructor which in turn creates and returns a function
reference.
12
Example Recursion
function factorial(number) {
if (number <= 0) // termination case
{
return 1;
} else
{
return (number * factorial(number - 1)); // function invokes itself
}
};
console.log(factorial(6)); // outputs 720
720
75
TypeScript
Hello
Lambda Functions
Lambda refers to anonymous functions in programming. Lambda functions are a concise
mechanism to represent anonymous functions. These functions are also called as Arrow
functions.
The fat arrow notation/lambda notation (=>): It is also called as the goes to
operator
Tip: By convention, the use of single letter parameter is encouraged for a compact and
precise function declaration.
Lambda Expression
It is an anonymous function expression that points to a single line of code. Its syntax is
as follows:
The program declares a lambda expression function. The function returns the sum of 10
and the argument passed.
76
TypeScript
110
Lambda Statement
Lambda statement is an anonymous function declaration that points to a block of code.
This syntax is used when the function body spans multiple lines. Its syntax is as follows:
110
Syntactic Variations
77
TypeScript
It is not mandatory to specify the data type of a parameter. In such a case the data type
of the parameter is any. Let us take a look at the following code snippet:
var func=(x)=>
{
if(typeof x=="number")
{
console.log(x+" is numeric")
}
else if(typeof x=="string")
{
console.log(x+" is a string")
}
}
func(12)
func("Tom")
12 is numeric
78
TypeScript
Tom is a string
var disp=()=>
{
console.log("Function invoked");
}
disp();
79
TypeScript
Function invoked
Function Overloads
Functions have the capability to operate differently on the basis of the input provided to
them. In other words, a program can have multiple methods with the same name with
different implementation. This mechanism is termed as Function Overloading. TypeScript
provides support for function overloading.
To overload a function in TypeScript, you need to follow the steps given below:
Step 1: Declare multiple functions with the same name but different function signature.
Function signature includes the following:
function disp(string):void;
function disp(number):void;
function disp(n1:number):void;
function disp(x:number,y:number):void;
function disp(n1:number,s1:string):void;
function disp(s:string,n:number):void;
Note: The function signature doesnt include the functions return type.
Step 2: The declaration must be followed by the function definition. The parameter types
should be set to any if the parameter types differ during overload. Additionally, for case
b explained above, you may consider marking one or more parameters as optional during
the function definition.
Example
Let us now take a look at the following example code:
80
TypeScript
function disp(s1:string):void;
function disp(n1:number,s1:string):void;
function disp(x:any,y?:any):void
{
console.log(x);
console.log(y);
}
disp("abc")
disp(1,"xyz");
The first two lines depict the function overload declaration. The function has two
overloads:
The third line defines the function. The data type of the parameters is set to any.
Moreover, the second parameter is optional here.
abc
1
xyz
81
10. TypeScript Numbers TypeScript
TypeScript like JavaScript supports numeric values as Number objects. A number object
converts numeric literal to an instance of the number class. The Number class acts as a
wrapper and enables manipulation of numeric literals as they were objects.
Syntax
var var_name=new Number(value)
Property Description
MIN_VALUE The smallest possible value a number in JavaScript can have 5E-
324
82
TypeScript
Example
console.log("TypeScript Number Properties: ");
console.log("Maximum value that a number variable can hold: " +
Number.MAX_VALUE);
console.log("The least value that a number variable can hold: " +
Number.MIN_VALUE);
console.log("Value of Negative Infinity: " + Number.NEGATIVE_INFINITY);
console.log("Value of Negative Infinity:" + Number.POSITIVE_INFINITY);
Example: NaN
var month=0
if( month<=0 || month >12)
{
month=Number.NaN
console.log("Month is "+ month)
}
else
{
console.log("Value Accepted..")
}
Month is NaN
83
TypeScript
Example: prototype
function employee(id:number,name:string)
{
this.id=id
this.name=name
}
var emp=new employee(123,"Smith")
employee.prototype.email="smith@abc.com"
console.log("Employee 's Id: "+emp.id)
console.log("Employee's name: "+emp.name)
console.log("Employee's Email ID: "+emp.email)
84
TypeScript
Number Methods
The Number object contains only the default methods that are a part of every object's
definition. Some of the commonly used methods are listed below:
Methods Description
toFixed() Formats a number with a specific number of digits to the right of the
decimal.
toLocaleString() Returns a string value version of the current number in a format that
may vary according to a browser's local settings.
Defines how many total digits (including digits to the left and right of
toPrecision() the decimal) to display of a number. A negative precision will throw
an error
toExponential()
This method returns a string representing the number object in exponential notation.
Syntax
number.toExponential( [fractionDigits] )
Parameter Details
fractionDigits An integer specifying the number of digits after the decimal point.
Defaults to as many digits as necessary to specify the number.
85
TypeScript
Return Value
A string representing a Number object in exponential notation with one digit before the
decimal point, rounded to fractionDigits digits after the decimal point. If the fractionDigits
argument is omitted, the number of digits after the decimal point defaults to the number
of digits necessary to represent the value uniquely.
Example
//toExponential()
var num1=1225.30
var val= num1.toExponential();
console.log(val)
1.2253e+3
toFixed()
This method formats a number with a specific number of digits to the right of the decimal.
Syntax
number.toFixed( [digits] )
Parameter Details
digits The number of digits to appear after the decimal point.
Return Value
A string representation of number that does not use exponential notation and has the
exact number of digits after the decimal place.
Example
var num3=177.234
console.log("num3.toFixed() is "+num3.toFixed())
console.log("num3.toFixed(2) is "+num3.toFixed(2))
console.log("num3.toFixed(6) is "+num3.toFixed(6))
86
TypeScript
num3.toFixed() is 177
num3.toFixed(2) is 177.23
num3.toFixed(6) is 177.234000
toLocaleString()
This method converts a number object into a human readable string representing the
number using the locale of the environment.
Syntax
number.toLocaleString()
Return Value
Returns a human readable string representing the number using the locale of the
environment.
Example
var num = new Number(177.1234);
console.log( num.toLocaleString());
177.1234
toPrecision()
This method returns a string representing the number object to the specified precision.
Syntax
number.toPrecision( [ precision ] )
Parameter Details
precision An integer specifying the number of significant digits.
87
TypeScript
Return Value
Returns a string representing a Number object in fixed-point or exponential notation
rounded to precision significant digits.
Example
var num = new Number(7.123456);
console.log(num.toPrecision());
console.log(num.toPrecision(1));
console.log(num.toPrecision(2));
7.123456
7
7.1
toString()
This method returns a string representing the specified object. The toString() method
parses its first argument, and attempts to return a string representation in the specified
radix (base).
Syntax
number.toString( [radix] )
Parameter Details
radix An integer between 2 and 36 specifying the base to use for representing
numeric values.
Return Value
Returns a string representing the specified Number object.
Example
var num = new Number(10);
console.log(num.toString());
console.log(num.toString(2));
console.log(num.toString(8));
88
TypeScript
10
1010
12
valueOf()
This method returns the primitive value of the specified number object.
Syntax
number.valueOf()
Return Value
Returns the primitive value of the specified number object.
Example
var num = new Number(10);
console.log(num.valueOf());
10
89
11. TypeScript Strings TypeScript
The String object lets you work with a series of characters. It wraps the string primitive
data type with a number of helper methods.
Syntax
var var_name = new String(string);
A list of the methods available in String object along with their description is given below:
Property Description
Constructor Returns a reference to the String function that created the object.
Prototype The prototype property allows you to add properties and methods to
an object.
90
TypeScript
Hello World
Length 11
Example:Object prototype
function employee(id:number,name:string)
{
this.id=id
this.name=name
}
var emp=new employee(123,"Smith")
employee.prototype.email="smith@abc.com"
console.log("Employee 's Id: "+emp.id)
console.log("Employee's name: "+emp.name)
console.log("Employee's Email ID: "+emp.email)
91
TypeScript
String Methods
A list of the methods available in String object along with their description is given below:
Method Description
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first
occurrence of the specified value, or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last
occurrence of the specified value, or -1 if not found.
substring() Returns the characters in a string between two indexes into the
string.
toLocaleLowerCase() The characters within a string are converted to lower case while
respecting the current locale.
toLocaleUpperCase() The characters within a string are converted to upper case while
respecting the current locale.
92
TypeScript
charAt
charAt() is a method that returns the character from the specified index. Characters in a
string are indexed from left to right. The index of the first character is 0, and the index of
the last character in a string, called stringName, is stringName.length 1.
Syntax
string.charAt(index);
Argument Details
index An integer between 0 and 1 less than the length of the string.
Return Value
Returns the character from the specified index.
Example
str.charAt(0) is:T
str.charAt(1) is:h
str.charAt(2) is:i
str.charAt(3) is:s
str.charAt(4) is:
93
TypeScript
str.charAt(5) is:i
charCodeAt()
This method returns a number indicating the Unicode value of the character at the given
index. Unicode code points range from 0 to 1,114,111. The first 128 Unicode code points
are a direct match of the ASCII character encoding. charCodeAt()always returns a value
that is less than 65,536.
Syntax
string.charCodeAt(index);
Argument Details
index An integer between 0 and 1 less than the length of the string; if
unspecified, defaults to 0.
Return Value
Returns a number indicating the Unicode value of the character at the given index. It
returns NaN if the given index is not between 0 and 1 less than the length of the string.
Example
str.charAt(0) is:84
str.charAt(1) is:104
str.charAt(2) is:105
str.charAt(3) is:115
str.charAt(4) is:32
str.charAt(5) is:105
94
TypeScript
concat()
This method adds two or more strings and returns a new single string.
Syntax
string.concat(string2, string3[, ..., stringN]);
Argument Details
string2...stringN These are the strings to be concatenated.
Return Value
Returns a single concatenated string.
Example
indexOf()
This method returns the index within the calling String object of the first occurrence of the
specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax
string.indexOf(searchValue[, fromIndex])
Argument Details
searchValue A string representing the value to search for.
fromIndex The location within the calling string to start the search from. It can
be any integer between 0 and the length of the string. The default value is 0.
Return Value
95
TypeScript
Example
lastIndexOf()
This method returns the index within the calling String object of the last occurrence of the
specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax
string.lastIndexOf(searchValue[, fromIndex])
Argument Details
searchValue A string representing the value to search for.
fromIndex The location within the calling string to start the search from. It can
be any integer between 0 and the length of the string. The default value is 0.
Return Value
Returns the index of the last found occurrence, otherwise -1 if not found.
Example
var str1 = new String( "This is string one and again string" );
var index = str1.lastIndexOf( "string" );
96
TypeScript
localeCompare()
This method returns a number indicating whether a reference string comes before or after
or is the same as the given string in sorted order.
Syntax
string.localeCompare( param )
Argument Details
param A string to be compared with string object.
Return Value
0 If the string matches 100%.
1 no match, and the parameter value comes before the string object's value in
the locale sort order
Example
97
TypeScript
localeCompare first :0
replace()
This method finds a match between a regular expression and a string, and replaces the
matched substring with a new substring.
The replacement string can include the following special replacement patterns
Pattern Inserts
$$ Inserts a "$".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n or $nn Where n or nn are decimal digits, inserts the nth parenthesized submatch
string, provided the first argument was a RegExp object.
Syntax
string.replace(regexp/substr, newSubStr/function[, flags]);
Argument Details
regexp A RegExp object. The match is replaced by the return value of parameter
#2.
newSubStr The String that replaces the substring received from parameter #1.
Return Value
It simply returns a new changed string.
Example
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
98
TypeScript
Example
var re = /(\w+)\s(\w+)/;
var str = "zara ali";
var newstr = str.replace(re, "$2, $1");
console.log(newstr);
ali, zara
search()
This method executes the search for a match between a regular expression and this String
object.
Syntax
string.search(regexp);
Argument Details
regexp A regular expression object. If a non-RegExp object obj is passed, it is
implicitly converted to a RegExp by using new RegExp(obj).
Return Value
If successful, the search returns the index of the regular expression inside the string.
Otherwise, it returns -1.
Example
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
99
TypeScript
if (str.search(re) == -1 )
{
console.log("Does not contain Apples" );
}
else
{
console.log("Contains Apples" );
}
Contains Apples
slice()
This method extracts a section of a string and returns a new string.
Syntax
string.slice( beginslice [, endSlice] );
Argument Details
Return Value
If successful, slice returns the index of the regular expression inside the string. Otherwise,
it returns -1.
Example
var str = "Apples are round, and apples are juicy.";
var sliced = str.slice(3, -2);
console.log(sliced);
100
TypeScript
split()
This method splits a String object into an array of strings by separating the string into
substrings.
Syntax
string.split([separator][, limit]);
Argument Details
separator Specifies the character to use for separating the string. If
separator is omitted, the array returned contains one element consisting of the
entire string.
Return Value
The split method returns the new array. Also, when the string is empty, split returns an
array containing one empty string, rather than an empty array.
Example
var str = "Apples are round, and apples are juicy.";
var splitted = str.split(" ", 3);
console.log(splitted)
substr()
This method returns the characters in a string beginning at the specified location through
the specified number of characters.
Syntax
101
TypeScript
string.substr(start[, length]);
Argument Details
start Location at which to start extracting characters (an integer between 0 and
one less than the length of the string).
Note If start is negative, substr uses it as a character index from the end of the string.
Return Value
The substr() method returns the new sub-string based on given parameters.
Example
var str = "Apples are round, and apples are juicy.";
console.log("(1,2): " + str.substr(1,2));
console.log("(-2,2): " + str.substr(-2,2));
console.log("(1): " + str.substr(1));
console.log("(-20, 2): " + str.substr(-20,2));
console.log("(20, 2): " + str.substr(20,2));
(1,2): pp
(-2,2): y.
(1): pples are round, and apples are juicy.
(-20, 2): nd
(20, 2): d
substring()
This method returns a subset of a String object.
Syntax
string.substring(indexA, [indexB])
102
TypeScript
Argument Details
indexA An integer between 0 and one less than the length of the string.
indexB (optional) An integer between 0 and the length of the string.
Return Value
The substring method returns the new sub-string based on given parameters.
Example
var str = "Apples are round, and apples are juicy.";
console.log("(1,2): " + str.substring(1,2));
console.log("(0,10): " + str.substring(0, 10));
console.log("(5): " + str.substring(5));
(1,2): p
(0,10): Apples are
(5): s are round, and apples are juicy.
toLocaleLowerCase()
This method is used to convert the characters within a string to lowercase while respecting
the current locale. For most languages, it returns the same output as toLowerCase.
Syntax
string.toLocaleLowerCase( )
Return Value
Returns a string in lowercase with the current locale.
Example
var str = "Apples are round, and Apples are Juicy.";
console.log(str.toLocaleLowerCase( ));
103
TypeScript
toLocaleUpperCase()
This method is used to convert the characters within a string to uppercase while respecting
the current locale. For most languages, it returns the same output as toUpperCase.
Syntax
string.toLocaleUpperCase( )
Return Value
Returns a string in uppercase with the current locale.
Example
var str = "Apples are round, and Apples are Juicy.";
console.log(str.toLocaleUpperCase( ));
toLowerCase()
This method returns the calling string value converted to lowercase.
Syntax
string.toLowerCase( )
Return Value
Returns the calling string value converted to lowercase.
Example
var str = "Apples are round, and Apples are Juicy.";
console.log(str.toLowerCase( ))
104
TypeScript
toString()
This method returns a string representing the specified object.
Syntax
string.toString( )
Return Value
Returns a string representing the specified object.
Example
var str = "Apples are round, and Apples are Juicy.";
console.log(str.toString( ));
toUpperCase()
This method returns the calling string value converted to uppercase.
Syntax
string.toUpperCase( )
Return Value
Returns a string representing the specified object.
Example
var str = "Apples are round, and Apples are Juicy.";
console.log(str.toUpperCase( ));
105
TypeScript
valueOf()
This method returns the primitive value of a String object.
Syntax
string.valueOf( )
Return Value
Returns the primitive value of a String object.
Example
var str = new String("Hello world");
console.log(str.valueOf( ));
Hello world
106
12. TypeScript Arrays TypeScript
Variables are scalar in nature. In other words, a variable declaration can only
contain a single at a time. This means that to store n values in a program n variable
declarations will be needed. Hence, the use of variables is not feasible when one
needs to store a larger collection of values.
TypeScript introduces the concept of arrays to tackle the same. An array is a homogenous
collection of values. To simplify, an array is a collection of values of the same data type.
It is a user defined type.
Features of an Array
Here is a list of the features of an array:
Arrays are static. This means that an array once initialized cannot be resized.
Array elements are identified by a unique integer called as the subscript / index of
the element.
Like variables, arrays too, should be declared before they are used. Use the var
keyword to declare an array.
Syntax
var array_name[:datatype]; //declaration
array_name=[val1,val2,valn..] //initialization
An array declaration without the data type is deemed to be of the type any. The type of
such an array is inferred from the data type of the arrays first element during initialization.
107
TypeScript
Arrays may be declared and initialized in a single statement. The syntax for the
same is:
array_name[subscript]=value
1
2
108
TypeScript
1
2
3
3
Array Object
An array can also be created using the Array object. The Array constructor can be passed
The following example shows how to create an array using this method.
Example
var arr_names:number[]=new Array(4)
for(var i=0;i<arr_names.length;i++)
{
arr_names[i]=i * 2
console.log(arr_names[i])
}
109
TypeScript
0
2
4
6
console.log(names[i])
}
Mary
Tom
Jack
Jill
110
TypeScript
Array Methods
A list of the methods of the Array object along with their description is given below.
Method Description
concat() Returns a new array comprised of this array joined with other array(s)
and/or value(s).
every() Returns true if every element in this array satisfies the provided testing
function.
filter() Creates a new array with all of the elements of this array for which the
provided filtering function returns true.
indexOf() Returns the first (least) index of an element within the array equal to
the specified value, or -1 if none is found.
lastIndexOf() Returns the last (greatest) index of an element within the array equal to
the specified value, or -1 if none is found.
map() Creates a new array with the results of calling a provided function on
every element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new
length of the array.
reduce() Apply a function simultaneously against two values of the array (from
left-to-right) as to reduce it to a single value.
reduceRight() Apply a function simultaneously against two values of the array (from
right-to-left) as to reduce it to a single value.
reverse() Reverses the order of the elements of an array -- the first becomes the
last, and the last becomes the first.
shift() Removes the first element from an array and returns that element.
111
TypeScript
some() Returns true if at least one element in this array satisfies the provided
testing function.
unshift() Adds one or more elements to the front of an array and returns the new
length of the array.
concat()
concat() method returns a new array comprised of this array joined with two or more
arrays.
Syntax
array.concat(value1, value2, ..., valueN);
Return Value
Returns a new array.
Example
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
alphaNumeric : a,b,c,1,2,3
every()
every() method tests whether all the elements in an array passes the test implemented
by the provided function.
112
TypeScript
Syntax
array.every(callback[, thisObject]);
Parameter Details
callback Function to test for each element.
Return Value
Returns true if every element in this array satisfies the provided testing function.
Example
function isBigEnough(element, index, array) {
return (element >= 10);
}
filter()
filter() method creates a new array with all elements that pass the test implemented by
the provided function.
Syntax
array.filter (callback[, thisObject]);
Parameter Details
callback Function to test for each element.
thisObject Object to use as this when executing callback.
113
TypeScript
Return Value
Returns created array.
Example
function isBigEnough(element, index, array) {
return (element >= 10);
}
forEach()
forEach() method calls a function for each element in the array
Syntax
array.forEach(callback[, thisObject]);
Parameter Details
callback Function to test for each element.
Return Value
Returns created array.
Example
var nums:number[]=new Array(12,13,14,15)
for(var i=0;i<nums.length;i++)
{
114
TypeScript
console.log(nums[i])
}
nums.reverse() //reverses the array element
console.log("Printing Reversed array....")
for(var i=0;i<nums.length;i++)
{
console.log(nums[i])
}
115
TypeScript
indexOf()
indexOf() method returns the first index at which a given element can be found in the
array, or -1 if it is not present.
Syntax
array.indexOf(searchElement[, fromIndex]);
Parameter Details
searchElement Element to locate in the array.
fromIndex The index at which to begin the search. Defaults to 0, i.e. the whole
array will be searched. If the index is greater than or equal to the length of the
array, -1 is returned.
Return Value
Returns the index of the found element.
Example
var index = [12, 5, 8, 130, 44].indexOf(8);
console.log("index is : " + index );
index is : 2
join()
join() method joins all the elements of an array into a string.
Syntax
array.join(separator);
Parameter Details
separator Specifies a string to separate each element of the array. If omitted,
the array elements are separated with a comma.
116
TypeScript
Return Value
Returns a string after joining all the array elements.
Example
var arr = new Array("First","Second","Third");
str : First,Second,Third
str : First, Second, Third
str : First + Second + Third
lastIndexOf()
lastIndexOf() method returns the last index at which a given element can be found in the
array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.
Syntax
array.lastIndexOf(searchElement[, fromIndex]);
Parameter Details
searchElement Element to locate in the array.
117
TypeScript
Return Value
Returns the index of the found element from the last.
Example
var index = [12, 5, 8, 130, 44].lastIndexOf(8);
console.log("index is : " + index );
index is : 3
map()
map() method creates a new array with the results of calling a provided function on every
element in this array.
Syntax
array.map(callback[, thisObject]);
Parameter Details
callback Function that produces an element of the new Array from an element
of the current one.
Return Value
Returns the created array.
Example
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
console.log("roots is : " + roots );
roots is : 1,2,3
118
TypeScript
pop()
pop() method removes the last element from an array and returns that element.
Syntax
array.pop();
Return Value
Returns the removed element from the array.
Example
var numbers = [1, 4, 9];
element is : 9
element is : 4
push()
push() method appends the given element(s) in the last of the array and returns the length
of the new array.
Syntax
array.push(element1, ..., elementN);
Parameter Details
element1, ..., elementN: The elements to add to the end of the array.
Return Value
Returns the length of the new array.
119
TypeScript
Example
var numbers = new Array(1, 4, 9);
var length = numbers.push(10);
console.log("new numbers is : " + numbers );
length = numbers.push(20);
console.log("new numbers is : " + numbers );
reduce()
reduce() method applies a function simultaneously against two values of the array (from
left-to-right) as to reduce it to a single value.
Syntax
array.reduce(callback[, initialValue]);
Parameter Details
callback Function to execute on each value in the array.
initialValue Object to use as the first argument to the first call of the callback.
Return Value
Returns the reduced single value of the array.
Example
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
console.log("total is : " + total );
total is : 6
120
TypeScript
reduceRight()
reduceRight() method applies a function simultaneously against two values of the array
(from right-to-left) as to reduce it to a single value
Syntax
array.reduceRight(callback[, initialValue]);
Parameter Details
callback Function to execute on each value in the array.
initialValue Object to use as the first argument to the first call of the callback.
Return Value
Returns the reduced right single value of the array.
Example
var total = [0, 1, 2, 3].reduceRight(function(a, b){ return a + b; });
console.log("total is : " + total );
total is : 6
reverse()
reverse() method reverses the element of an array. The first array element becomes the
last and the last becomes the first.
Syntax
array.reverse();
Return Value
Returns the reversed single value of the array.
Example
var arr = [0, 1, 2, 3].reverse();
console.log("Reversed array is : " + arr );
121
TypeScript
shift()
shift()method removes the first element from an array and returns that element.
Syntax
array.shift();
Return Value
Returns the removed single value of the array
Example
var arr = [10, 1, 2, 3].shift();
console.log("Shifted value is : " + arr );
Shifted value is : 10
slice()
slice() method extracts a section of an array and returns a new array.
Syntax
array.slice( begin [,end] );
Parameter Details
begin Zero-based index at which to begin extraction. As a negative index, start
indicates an offset from the end of the sequence.
122
TypeScript
Return Value
Returns the extracted array based on the passed parameters.
Example
var arr = ["orange", "mango", "banana", "sugar", "tea"];
console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) );
console.log("arr.slice( 1, 3) : " + arr.slice( 1, 3) );
arr.slice( 1, 2) : mango
arr.slice( 1, 3) : mango,banana
some()
some() method tests whether some element in the array passes the test implemented by
the provided function.
Syntax
array.some(callback[, thisObject]);
Parameter Details
callback Function to test for each element.
thisObject Object to use as this when executing callback.
Return Value
If some element passes the test, then it returns true, otherwise false.
Example
function isBigEnough(element, index, array)
{
return (element >= 10);
123
TypeScript
sort()
sort() method sorts the elements of an array.
Syntax
array.sort( compareFunction );
Parameter Details
compareFunction Specifies a function that defines the sort order. If omitted,
the array is sorted lexicographically.
Return Value
Returns a sorted array.
Example
var arr = new Array("orange", "mango", "banana", "sugar");
var sorted = arr.sort();
console.log("Returned string is : " + sorted );
splice()
splice() method changes the content of an array, adding new elements while removing old
elements.
124
TypeScript
Syntax
array.splice(index, howMany, [element1][, ..., elementN]);
Parameter Details
index Index at which to start changing the array.
element1, ..., elementN The elements to add to the array. If you don't
specify any elements, splice simply removes the elements from the array.
Return Value
Returns the extracted array based on the passed parameters.
Example
var arr = ["orange", "mango", "banana", "sugar", "tea"];
125
TypeScript
toString()
toString() method returns a string representing the source code of the specified array
and its elements.
Syntax
array.toString();
Return Value
Returns a string representing the array.
Example
var arr = new Array("orange", "mango", "banana", "sugar");
var str = arr.toString();
console.log("Returned string is : " + str );
unshift()
unshift() method adds one or more elements to the beginning of an array and returns
the new length of the array.
Syntax
array.unshift( element1, ..., elementN );
Parameter Details
element1, ..., elementN The elements to add to the front of the array.
Return Value
Returns the length of the new array. It returns undefined in IE browser.
Example
var arr = new Array("orange", "mango", "banana", "sugar");
var length = arr.unshift("water");
console.log("Returned array is : " + arr );
126
TypeScript
Array Destructuring
Refers to breaking up the structure of an entity. TypeScript supports destructuring when
used in the context of an array.
Example
var arr:number[]=[12,13]
var[x,y]=arr
console.log(x)
console.log(y)
12
13
var j:any;
var nums:number[]=[1001,1002,1003,1004]
for(j in nums)
{
127
TypeScript
console.log(nums[j])
}
1001
1002
1003
1004
Arrays in TypeScript
TypeScript supports the following concepts in arrays:
Concept Description
Passing arrays to functions You can pass to the function a pointer to an array by
specifying the array's name without an index.
Multidimensional Arrays
An array element can reference another array for its value. Such arrays are called as multi-
dimensional arrays. TypeScript supports the concept of multi-dimensional arrays. The
simplest form of a multi-dimensional array is a two-dimensional array.
128
TypeScript
Example
var multi:number[][]=[[1,2,3],[23,24,25]]
console.log(multi[0][0])
console.log(multi[0][1])
console.log(multi[0][2])
console.log(multi[1][0])
console.log(multi[1][1])
console.log(multi[1][2])
The above example initially declares an array with 2 elements. Each of these elements
refer to another array having 3 elements. The pictorial representation of the above array
is given below.
While referring to an array element here, the subscript of the initial array element must
be followed by the subscript of the referenced array element. This is illustrated in the code.
129
TypeScript
console.log(multi[0][0]);
console.log(multi[0][1]);
console.log(multi[0][2]);
console.log(multi[1][0]);
console.log(multi[1][1]);
console.log(multi[1][2]);
1
2
3
23
24
25
function disp(arr_names:string[])
{
for(var i=0;i<arr_names.length;i++)
{
console.log(names[i])
}
disp(names)
130
TypeScript
function disp(arr_names) {
for (var i = 0; i < arr_names.length; i++) {
console.log(names[i]);
}
}
disp(names);
Mary
Tom
Jack
Jill
var nums:string[]=disp()
for(var i in nums)
{
console.log(nums[i])
}
131
TypeScript
Mary
Tom
Jack
Jill
132
13. TypeScript Tuples TypeScript
At times, there might be a need to store a collection of values of varied types. Arrays will
not serve this purpose. TypeScript gives us a data type called tuple that helps to achieve
such a purpose.
Syntax
var tuple_name=[value1,value2,value3,value n]
For Example:
var mytuple=[10,"Hello"];
You can also declare an empty tuple in Typescript and choose to initialize it later.
var mytuple=[];
mytuple[0]=120
mytuple[1]=234
Syntax
tuple_name[index]
133
TypeScript
In the above example, a tuple, mytuple, is declared. The tuple contains values of numeric
and string types respectively.
10
Hello
12
23
Tuple Operations
Tuples in TypeScript supports various operations like pushing a new item, removing an
item from the tuple, etc.
Example
var mytuple=[10,"Hello","World","typeScript"];
console.log("Items before push "+mytuple.length) // returns the tuple size
mytuple.push(12) // append value to the tuple
console.log("Items after push "+mytuple.length)
console.log("Items before pop "+mytuple.length)
console.log(mytuple.pop()+" popped from the tuple") // removes and returns the
// last item
134
TypeScript
Updating Tuples
Tuples are mutable which means you can update or change the values of tuple elements.
Example
Destructuring a Tuple
Destructuring refers to breaking up the structure of an entity. TypeScript supports
destructuring when used in the context of a tuple.
Example
var a =[10,"hello"]
var [b,c]=a
console.log( b )
console.log( c )
135
TypeScript
10
hello
136
14. TypeScript Union TypeScript
TypeScript 1.4 gives programs the ability to combine one or two types. Union types are a
powerful way to express a value that can be one of the several types. Two or more data
types are combined using the pipe symbol (|) to denote a Union Type. In other words, a
union type is written as a sequence of types separated by vertical bars.
In the above example, the variables type is union. It means that the variable can contain
either a number or a string as its value.
137
TypeScript
{
console.log(name)
}
else
{
var i;
for(i=0;i<name.length;i++)
{
console.log(name[i])
}
}
}
disp("mark")
console.log("Printing names array....")
disp(["Mark","Tom","Mary","John"])
The function disp() can accept argument either of the type string or a string array.
138
TypeScript
Mark
Printing names array.
Mark
Tom
Mary
John
for(i=0;i<arr.length;i++)
{
console.log(arr[i])
}
arr=["Mumbai","Pune","Delhi"]
console.log("**string array**")
for(i=0;i<arr.length;i++)
{
console.log(arr[i])
}
The program declares an array. The array can represent either a numeric collection or a
string collection.
139
TypeScript
**numeric array**
1
2
4
**string array**
Mumbai
Pune
Delhi
140
15. TypeScript Interfaces TypeScript
An interface is a syntactical contract that an entity should conform to. In other words, an
interface defines the syntax that any entity must adhere to.
Interfaces define properties, methods, and events, which are the members of the
interface. Interfaces contain only the declaration of the members. It is the responsibility
of the deriving class to define the members. It often helps in providing a standard structure
that the deriving classes would follow.
var person={
FirstName:"Tom",
LastName:"Hanks",
sayHi: ()=>{ return "Hi"}
};
{
FirstName:string,
LastName:string,
sayHi()=>string
}
Declaring Interfaces
The interface keyword is used to declare an interface. Here is the syntax to declare an
interface:
Syntax
interface interface_name
{
}
141
TypeScript
The example defines an interface. The customer object is of the type IPerson. Hence, it
will now be binding on the object to define all properties as specified by the interface.
Another object with following signature, is still considered as IPerson because that object
is treated by its size or signature.
142
TypeScript
Customer object
Tom
Hanks
Hi there
Employee object
Jim
Blakes
Hello!!!
Interfaces are not to be converted to JavaScript. Its just part of TypeScript. If you see
the screen shot of TS Playground tool there is no java script emitted when you declare an
interface unlike a class. So interfaces have zero runtime JavaScript impact.
interface RunOptions
{
program:string;
commandline:string[]|string|(()=>string);
143
TypeScript
}
//commandline as string
var options:RunOptions={program:"test1",commandline:"Hello"};
console.log(options.commandline)
var fn:any=options.commandline;
console.log(fn());
144
TypeScript
Hello
Hello
World
**Hello World**
Example
interface namelist
{
[index:number]:string
}
var list2:namelist=["John",1,"Bran"] //Error. 1 is not type string
interface ages
{
[index:string]:number
}
var agelist:ages;
agelist["John"]=15 // Ok
agelist[2]="nine" // Error
145
TypeScript
Age: 27
Instrument: Drums
146
TypeScript
interface IParent1
{ v1:number }
interface IParent2
{ v2:number }
interface Child extends IParent1, IParent2
{ }
var Iobj:Child={ v1:12, v2:23}
console.log("value 1: "+this.v1+" value 2: "+this.v2)
The object Iobj is of the type interface leaf. The interface leaf by the virtue of inheritance
now has two attributes- v1 and v2 respectively. Hence, the object Iobj must now contain
these attributes.
value 1: 12 value 2: 23
147
16. TypeScript Classes TypeScript
Creating classes
Use the class keyword to declare a class in TypeScript. The syntax for the same is given
below:
Syntax
class class_name
{
//class scope
}
The class keyword is followed by the class name. The rules for identifiers must be
considered while naming a class.
Fields: A field is any variable declared in a class. Fields represent data pertaining
to objects
Constructors: responsible for allocating memory for the objects of the class
Functions: Functions represent actions an object can take. They are also at times referred
to as methods
These components put together are termed as the data members of the class.
class Person
{
148
TypeScript
//function
disp():void
{
console.log("Engine is : "+this.engine)
}
}
The example declares a class Car. The class has a field named engine. The var keyword
is not used while declaring a field. The example above declares a constructor for the class.
A constructor is a special function of the class that is responsible for initializing the
variables of the class. TypeScript defines a constructor using the constructor keyword. A
constructor is a function and hence can be parameterized.
The this keyword refers to the current instance of the class. Here, the parameter name
and the name of the classs field are the same. Hence to avoid ambiguity, the classs field
is prefixed with the this keyword.
disp() is a simple function definition. Note that the function keyword is not used here.
149
TypeScript
Syntax
var object_name= new class_name([ arguments ])
The right-hand side of the expression invokes the constructor. The constructor
should be passed values if it is parameterized.
//accessing an attribute
obj.field_name
//accessing a function
obj.function_name()
150
TypeScript
//function
disp():void
{
console.log("Function displays Engine is : "+this.engine)
}
}
//create an object
var obj= new Car("XXSY1")
151
TypeScript
};
return Car;
}());
//create an object
var obj = new Car("XXSY1");
//access the field
console.log("Reading attribute value Engine as : " + obj.engine);
//access the function
obj.disp();
Class Inheritance
TypeScript supports the concept of Inheritance. Inheritance is the ability of a program to
create new classes from an existing class. The class that is extended to create newer
classes is called the parent class/super class. The newly created classes are called the
child/sub classes.
A class inherits from another class using the extends keyword. Child classes inherit all
properties and methods except constructors from the parent class.
Syntax
class child_class_name extends parent_class_name
152
TypeScript
{
disp():void
{ console.log("Area of the circle: "+this.Area) }
}
153
TypeScript
The above example declares a class Shape. The class is extended by the Circle class. Since
there is an inheritance relationship between the classes, the child class i.e. the class Car
gets an implicit access to its parent class attribute i.e. area.
Single: Every class can at the most extend from one parent class
Multiple: A class can inherit from multiple classes. TypeScript doesnt support
multiple inheritance.
class Root
{
str:string;
}
class Child extends Root
{}
class Leaf extends Child //indirectly inherits from Root by virtue of
inheritance
{}
var obj= new Leaf();
obj.str="hello"
console.log(obj.str)
The class Leaf derives the attributes from Root and Child classes by virtue of multi-level
inheritance.
154
TypeScript
hello
class PrinterClass
{
doPrint():void
{console.log("doPrint() from Parent called") }
}
class StringPrinter extends PrinterClass
{
doPrint():void
{
super.doPrint()
console.log("doPrint() is printing a string") }
155
TypeScript
}
var obj= new StringPrinter()
obj.doPrint()
The super keyword is used to refer to the immediate parent of a class. The keyword can
be used to refer to the super class version of a variable, property or method. Line 13
invokes the super class version of the doWork() function.
156
TypeScript
Example
class StaticMem
{
static num:number;
static disp():void
{
console.log("The value of num is"+ StaticMem.num)
}
}
StaticMem.num=12 // initialize the static variable
StaticMem.disp() // invoke the static method
157
TypeScript
Example
class Person{ }
var obj=new Person()
var isPerson=obj instanceof Person;
console.log(" obj is an instance of Person " + isPerson);
Data Hiding
A class can control the visibility of its data members to members of other classes. This
capability is termed as Data Hiding or Encapsulation.
Object Orientation uses the concept of access modifiers or access specifiers to implement
the concept of Encapsulation. The access specifiers/modifiers define the visibility of a
classs data members outside its defining class.
158
TypeScript
Private data members are accessible only within the class that
private defines these members. If an external class member tries to
access a private member, the compiler throws an error
Example
Let us now take an example to see how data hiding works:
class Encapsulate
{
str:string="hello"
private str2:string="world"
}
var obj=new Encapsulate()
console.log(obj.str) //accessible
console.log(obj.str2) //compilation Error as str2 is private
The class has two string attributes, str1 and str2, which are public and private members
respectively. The class is instantiated. The example returns a compile time error, as the
private attribute str2 is accessed outside the class that declares it.
interface ILoan
{
interest:number
}
159
TypeScript
interest:number
rebate:number
constructor(interest:number,rebate:number)
{
this.interest=interest
this.rebate=rebate
}
}
var obj= new AgriLoan(10,1)
console.log("Interest is : "+obj.interest+" Rebate is : "+obj.rebate )
The class AgriLoan implements the interface Loan. Hence, it is now binding on the class to
include the property interest as its member.
Intrest is 10 Rebate is 1
160
17. TypeScript Objects TypeScript
An object is an instance which contains set of key value pairs. The values can be scalar
values or functions or even array of other objects. The syntax is given below:
Syntax
var object_name={
key1: value1, //scalar value
key2: value,
key3: function()
{
//functions
},
key4:[content1, content2] //collection
};
As shown above, an object can contain scalar values, functions and structures like arrays
and tuples.
Tom
Hanks
161
TypeScript
var person = {
firstname:"Tom",
lastname:"Hanks"
};
In case you want to add some value to an object, JavaScript allows you to make the
necessary modification. Suppose we need to add a function to the person object later this
is the way you can do this.
If you use the same code in Typescript the compiler gives an error. This is because in
Typescript, concrete objects should have a type template. Objects in Typescript must be
an instance of a particular type.
person.sayHello()
hello Tom
162
TypeScript
The example declares an object literal. The function expression is invoked passing person
object.
163
TypeScript
Duck-typing
In duck-typing, two objects are considered to be of the same type if both share the same
set of properties. Duck-typing verifies the presence of certain properties in the objects,
rather than their actual type, to check their suitability. The concept is generally explained
by the following phrase:
When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I
call that bird a duck.
The TypeScript compiler implements the duck-typing system that allows object creation
on the fly while keeping type safety. The following example shows how we can pass objects
that dont explicitly implement an interface but contain all of the required members to a
function.
164
TypeScript
Example
interface IPoint
{
x:number
y:number
}
function addPoints(p1:IPoint,p2:IPoint):IPoint
{
var x=p1.x+p2.x
var y=p1.y+p2.y
return {x:x,y:y}
}
//Valid
var newPoint=addPoints({x:3,y:4},{x:5,y:1})
//Error
var newPoint2=addPoints({x:1},{x:4,y:3})
165
18. TypeScript Namespaces TypeScript
A namespace is a way to logically group related code. This is inbuilt into TypeScript unlike
in JavaScript where variables declarations go into a global scope and if multiple JavaScript
files are used within same project there will be possibility of overwriting or misconstruing
the same variables, which will lead to the global namespace pollution problem in
JavaScript.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace
name as follows:
namespace SomeNameSpaceName
{
export interface ISomeInterfaceName { }
export class SomeClassName { }
}
The classes or interfaces which should be accessed outside the namespace should be
marked with keyword export.
SomeNameSpaceName.SomeClassName;
If the first namespace is in separate TypeScript file, then it should be referenced using
triple slash reference syntax.
FileName :IShape.ts
----------
namespace Drawing{
export interface IShape{
draw();
}
}
166
TypeScript
FileName :Circle.ts
----------
/// <reference path="IShape.ts" />
namespace Drawing{
public draw(){
console.log("Circle is drawn");
}
FileName :Triangle.ts
----------
/// <reference path="IShape.ts" />
namespace Drawing{
public draw(){
console.log("Triangle is drawn");
}
}
FileName : TestShape.ts
/// <reference path="IShape.ts" />
/// <reference path="Circle.ts" />
/// <reference path="Triangle.ts" />
function drawAllShapes(shape:Drawing.IShape){
shape.draw();
}
drawAllShapes(new Drawing.Circle());
drawAllShapes(new Drawing.Triangle());
167
TypeScript
The above code can be compiled and executed using the following command
node app.js
168
TypeScript
When the above code is compiled and executed, it produces the following result:
Circle is drawn
Triangle is drawn
Nested Namespaces
You can define one namespace inside another namespace as follows:
namespace namespace_name1
{
export namespace namespace_name2
{
export class class_name { }
}
}
You can access members of nested namespace by using the dot (.) operator as follows:
FileName : Invoice.ts
namespace tutorialPoint {
export namespace invoiceApp {
export class Invoice {
public calculateDiscount(price: number) {
return price * .40;
}
}
}
}
FileName: InvoiceTest.ts
/// <reference path="Invoice.ts" />
169
TypeScript
The above code can be compiled and executed using the following command
When the above code is compiled and executed, it produces the following result:
200
170
19. TypeScript Modules TypeScript
A module is designed with the idea to organize code written in TypeScript. Modules are
broadly divided into
Internal Modules
External Modules
Internal Module
Internal modules came in earlier version of Typescript. This was used to logically group
classes, interfaces, functions into one unit and can be exported in another module. This
logical grouping is named namespace in latest version of TypeScript. So internal modules
are obsolete instead we can use namespace. Internal modules are still supported, but its
recommended to use namespace over internal modules.
171
TypeScript
External Module
External modules in TypeScript exists to specify and load dependencies between multiple
external js files. If there is only one js file used, then external modules are not relevant.
Traditionally dependency management between JavaScript files was done using browser
script tags (<script></script>). But thats not extendable, as its very linear while loading
modules. That means instead of loading files one after other there is no asynchronous
option to load modules. When you are programming js for the server for example NodeJs
you dont even have script tags.
There are two scenarios for loading dependents js files from a single main JavaScript file.
If you are migrating TypeScript from AMD to CommonJs module systems, then there is no
additional work needed. The only thing you need to change is just the compiler flag Unlike
in JavaScript there is an overhead in migrating from CommonJs to AMD or vice versa.
The syntax for declaring an external module is using keyword export and import
//FileName : SomeInterface.ts
export interface SomeInterface{
//code declarations
}
To use the declared module in another file, an import keyword is used as given below. The
file name is only specified no extension used.
172
TypeScript
Example
Lets understand this using an example.
// IShape.ts
export interface IShape {
draw();
}
// Circle.ts
import shape = require("./IShape");
export class Circle implements shape.IShape{
public draw(){
console.log("Cirlce is drawn (external module)");
}
}
// Triangle.ts
import shape = require("./IShape");
export class Triangle implements shape.IShape{
public draw(){
console.log("Triangle is drawn (external module)");
}
}
// TestShape.ts
import shape = require("./IShape");
import circle = require("./Circle");
import triangle = require("./Triangle");
173
TypeScript
The command to compile the main TypeScript file for AMD systems is:
File: IShape.js
//Generated by typescript 1.8.10
define(["require", "exports"], function (require, exports) {
});
File: Circle.js
//Generated by typescript 1.8.10
define(["require", "exports"], function (require, exports) {
var Circle = (function () {
function Circle() {
}
Circle.prototype.draw = function () {
console.log("Cirlce is drawn (external module)");
};
return Circle;
})();
exports.Circle = Circle;
});
File:Triangle.js
//Generated by typescript 1.8.10
define(["require", "exports"], function (require, exports) {
var Triangle = (function () {
function Triangle() {
}
Triangle.prototype.draw = function () {
console.log("Triangle is drawn (external module)");
};
return Triangle;
})();
exports.Triangle = Triangle;
174
TypeScript
});
File:TestShape.js
//Generated by typescript 1.8.10
define(["require", "exports", "./Circle", "./Triangle"], function (require,
exports, circle, triangle) {
function drawAllShapes(shapeToDraw) {
shapeToDraw.draw();
}
drawAllShapes(new circle.Circle());
drawAllShapes(new triangle.Triangle());
});
The command to compile the main TypeScript file for Commonjs systems is
File:Circle.js
//Generated by typescript 1.8.10
var Circle = (function () {
function Circle() {
}
Circle.prototype.draw = function () {
console.log("Cirlce is drawn");
};
return Circle;
})();
exports.Circle = Circle;
File:Triangle.js
//Generated by typescript 1.8.10
var Triangle = (function () {
function Triangle() {
}
Triangle.prototype.draw = function () {
175
TypeScript
File:TestShape.js
//Generated by typescript 1.8.10
var circle = require("./Circle");
var triangle = require("./Triangle");
function drawAllShapes(shapeToDraw) {
shapeToDraw.draw();
}
drawAllShapes(new circle.Circle());
drawAllShapes(new triangle.Triangle());
Output
Cirlce is drawn (external module)
Triangle is drawn (external module)
176
20. TypeScript Ambients TypeScript
Ambient declarations are a way of telling the TypeScript compiler that the actual source
code exists elsewhere. When you are consuming a bunch of third party js libraries like
jquery/angularjs/nodejs you cant rewrite it in TypeScript. Ensuring typesafety and
intellisense while using these libraries will be challenging for a TypeScript programmer.
Ambient declarations help to seamlessly integrate other js libraries into TypeScript.
Defining Ambients
Ambient declarations are by convention kept in a type declaration file with following
extension (d.ts)
Sample.d.ts
The above file will not be transcompiled to JavaScript. It will be used for type safety and
intellisense.
The ambient files should be referenced in the client TypeScript file as shown
Example
Lets understand this with help of an example. Assume you been given a third party
JavaScript library which contains code similar to this.
FileName: CalcThirdPartyJsLib.js
var TutorialPoint;
(function (TutorialPoint) {
177
TypeScript
var sum = 0;
for (var i = 0; i <= limit; i++) {
Calc.prototype.doSum = function (limit) {
var sum = 0;
for (var i = 0; i <= limit; i++)
{
sum = sum + i;
return sum;
return Calc;
TutorialPoint.Calc = Calc;
})(TutorialPoint || (TutorialPoint = {}));
var test = new TutorialPoint.Calc();
As a typescript programmer you will not have time to rewrite this library to typescript. But
still you need to use the doSum() method with type safety. What you could do is ambient
declaration file. Let us create an ambient declaration file Calc.d.ts
FileName: Calc.d.ts
declare module TutorialPoint {
export class Calc {
doSum(limit:number) : number;
}
}
Ambient files will not contain the implementations; they are just type declarations.
Declarations now need to be included in the typescript file as follows.
FileName : CalcTest.ts
The following line of code will show a compiler error. This is because in the declaration file
we specified the input parameter will be number.
178
TypeScript
obj.doSum("Hello");
Comment the above line and compile the program using the following syntax:
tsc CalcTest.ts
In order to execute the code, let us add an html page with script tags as given below. Add
the compiled CalcTest.js file and the third party library file CalcThirdPartyJsLib.js.
<html>
<body style="font-size:30px;">
<h1>Ambient Test</h1>
<h2>Calc Test</h2>
</body>
<script src="CalcThirdPartyJsLib.js"></script>
<script src="CalcTest.js"></script>
</html>
179
TypeScript
55
Similarly, you can integrate jquery.d.ts or angular.d.ts into a project, based on your
requirement.
180