SlideShare a Scribd company logo
TypescriptBasics
M.Manikandan- MMK
TypeScript
TypeScript is a superset of JavaScript which primarily provides optional static typing, classes
and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for
spotting common errors as you type the code.
TypeScript doesn’t run in the browser. The code written in typescript is compiled to
JavaScript, which then runs in the browser.
TypeScript is open source. It was designed by Anders Hejlsberg (the lead architect of C#) at
Microsoft.
Features of TypeScript:
1. The code written in typescript is compiled to the JavaScript for the purpose of
execution.
2. As we already discussed that the code written in typescript is compiled to the
JavaScript which can reuse all of the existing JavaScript frameworks, tools, and
libraries.
3. As TypeScript is a superset of JavaScript so any valid .js file can be renamed to .ts
and compiled with other TypeScript files.
4. TypeScript is portable i.e. it can run on any environment that JavaScript runs on.
5. TypeScript provides optional static typing. JavaScript is dynamically typed. This
means JavaScript does not know what type a variable is until it actsually instantiated
at run-time. This also means that it may be too late. TypeScript adds type support to
JavaScript. TypeScript makes typing a bit easier and a lot less explicit by the usage of
type inference. For example: var msg = “hello” in TypeScript is the same as var msg :
string = “hello”. TLS (TypeScript Language Service) provides the facility to identify
the type of the variable based on its value if it is declared with no type.
6. TypeScript supports Object Oriented Programming concepts like classes, object,
interfaces and inheritance etc.
7. TypeScript Definition file with .d.ts extension provides definition for external
JavaScript libraries.
8. TypeScript provides strict null checks. TypeScript compiler will not allow undefined
to be assigned to a variable unless you explicitly declare it to be of nullable type. For
example, let num1 : number = undefined will result in a compile error. This fits
perfectly with type theory, since undefined is not a number. One can define x to be a
sum type of number and undefined to
correct this: let num1 : number |
undefined = undefined.
TypescriptBasics
M.Manikandan- MMK
JavaScript:
JavaScript is the most popular programming language. It is lightweight and
commonly used to create interactive and dynamic web pages. It is developed by Netscape in
1995 and named as LiveScript which is later renamed to JavaScript. Read more on
JavaScript.
TypeScript:
TypeScript: TypeScript is a superset of JavaScript which primarily provides optional
static typing, classes and interfaces. One of the big benefits is to enable IDEs to
provide a richer environment for spotting common errors as you type the code.
Differences betweenjavascriptand typescript:
Javascript Typescript
JavaScript is a scripting language.
TypeScript supports object oriented
programming language concepts.
There is no static typing. ex: var num. TypeScript supports optional static typing
JavaScript doesn’t supports interfaces. TypeScript supports interfaces.
JavaScript has no optional parameter
feature.
TypeScript has optional parameter feature.
JavaScript doesn’t supports generics. TypeScript Supports generics.
JavaScript doesn’t have modules support.
Number, string etc. are the objects.
TypeScript supports modules .
Number, string etc. are the interfaces.
Difference Between Var And Let
var keyword:
The var statement is used to declare a variable. We can
TypescriptBasics
M.Manikandan- MMK
optionally initialize the value of that variable.
Example: var num =10;
let keyword:
The let statement is used to declare a local variable in a block scope. It is similar to
var, in that we can optionally initialize the variable.
Example: let num =10;
Scope difference between var and let:
Var scope:
The var is scoped to the nearest function block. In the below example variable num2
is declared within a block but can be accessed within the function and outside this block. The
statement in which we are using this variable should be after this block which means we
cannot access num2 before the declaration statement.
function varTest(){
var num1 =10;
console.log(num1); //output 10
if(true){
var num2=20;
console.log(num2); //output 20
}
console.log(num1); //output 10
console.log(num2); //output 20
}
Let scope:
The let is scoped to the nearest enclosing block. In the below example variable num2
is declared within a block and cannot be accessed outside this block.
function letTest(){
var num1 =10;
console.log(num1); //output 10
if(true){
var num2=20;
console.log(num2); //output 20
}
console.log(num1); //output 10
console.log(num2); //Cannot be accessed here
TypescriptBasics
M.Manikandan- MMK
}
Redeclaration difference between var and let:
Redeclarationwith var:
The var keyword provides the facility to re-declare the same variable in the same scope.
function varTest(){
var num1 = 10;
var num1 = 20; //num1 is replaced
}
Redeclaration with let: The let keyword does not provides the facility to re-declare the same
variable in the same scope.
function letTest(){
var num1 = 10;
var num1 = 20; // SyntaxError: Identifier num1 has already been declared
}
Typescript Hello World
Let us start TypeScript programming with simple “Hello World!” example.
Create and save the file with .ts extension. In first line we declare a variable of string type. In
second line we display the variable’s value at the terminal window.
TypeScript Hello World:
var message:string = "Hello World!" ;
console.log(message);
As we discussed in earlier tutorials that TypeScript code will be converted into JavaScript
Code. After the compilation of above TypeScript code following JavaScript code will be
generated.
Translatedcode:
var message = "Hello World!";
console.log(message);
Compile and Execute a TypeScript Program:
Comiple: Use below command on the terminal window for compilation.
tsc typeScriptFileName.ts
Note − Multiple files can be compiled at once.
tsc typeScriptFileName1.ts, typeScriptFileName2.ts,
typeScriptFileName3.ts
Execute: Use below command on the terminal
TypescriptBasics
M.Manikandan- MMK
window for execution.
node typeScriptFileName.js
TypescriptBasics
M.Manikandan- MMK
The let keyword does not provides the facility to re-declare the same variable in the same scope.
TypeScript Data Types System
When a variable is declared some part of memory is reserved. But how much memory will be
reserved. It depends upon the data type of the variable. i.e. how much memory will be reserved
and which type of data can be stored in reserved memory is depends upon data type of the
variable. The Type System of a language represents these data types.
Data types in TypeScript:
1. Any Type: represents the super type of all data types in TypeScript. TypeScript provides
the compile time data type-checking for the variables. In some situation we may not know
what type of value for variable will come. These values may come from dynamic content
e.g. from the user. In such cases, we want to opt-out of type-checking and let the values
pass through compile-time checks. The any type is used for these variables.
2. Built-in types:
Data type Keyword Description
Number number
It represents a double precision 64-bit
floating point values which can be used to
represent both integers and fractions.
String string It represents a sequence of characters.
Boolean boolean It represents logical values true and false.
Void void
It is used on function return types to
represent non-returning functions.
Null null
It is used to represent an intentional
absence of an object value.
Undefined undefined It represents uninitialized variables.
3. User-defined types: include Enumerations (enums), classes, interfaces, arrays, and tuple.
Variables In Typescript
Variable is the name of reserved memory location. It means when we declare a variable some part
of memory is reserved.
Rules for declaring a TypeScript variable:
1. TypeScript variable name must begin with a letter, underscore, or dollar sign.
2. TypeScript variable names are case sensitive.
3. TypeScript reserved keywords like abstract, boolean etc can’t be used as TypeScript
variable name.
Variable Declaration in TypeScript
TypescriptBasics
M.Manikandan- MMK
TypeScript Switch Statement
TypeScript switch statement is used to execute a block of statement based on the switch
expression value. It is like if else if statement.
Syntax:
switch(expression){
case value1:
//TypeScript block of statements
break;
case value2:
//TypeScript block of statements
break;
...
default:
//TypeScript block of statements
break;
}
TypeScript Switch Statement Example:
var today:string;
switch (new Date().getDay()) {
case 0:
today = "Sunday";
break;
case 1:
today = "Monday";
break;
case 2:
today = "Tuesday";
break;
case 3:
TypescriptBasics
M.Manikandan- MMK
today = "Wednesday";
break;
case 4:
today = "Thursday";
break;
case 5:
today = "Friday";
break;
case 6:
today = "Saturday";
}
console.log("Today is "+ today);
TypeScript For Loop
The for loop repeatedly executes a block of statements until a particular condition is true.
Syntax:
for(initialization; condition; statement){
//Block of statements
}
Where:
initialization statement: is used to initialize the loop variable.
boolean expression: is used for condition check whether returns true or false.
statement: is used for either increment or decrements the loop variable.
TypeScript for loop example:
for (num=1; num<=10; num++) {
console.log(num);
}
Break Statement:
The break statement is a control statement which is used to jump out of the loop.
Syntax:
TypescriptBasics
M.Manikandan- MMK
for( initialization; condition; statement){
//Block of statements
if(condition){
break;
}
}
Typescript for loop break example:
for (num=1; num<=10; num++) {
if(num==6){
break;
}
console.log(num);
}
Continue statement:
The continue statement is a control statement which is used to skip the following statement in
the body of the loop and continue with the next iteration of the loop.
Syntax:
for( initialization; condition; statement){
//Block of statements
if(condition){
continue;
}
}
TypeScript for loop continue example:
for (num=1; num<=10; num++) {
if(num==6){
continue;
}
console.log(num);
}
TypescriptBasics
M.Manikandan- MMK
TypeScript For In Loop
The for in loop is used to iterate the properties of an object.
Syntax:
for(property in object){
//Block of statements
}
TypeScript for in loop example:
var person = {Fname:"Rajeev", Lname:"Johari", Age:40};
var perproperty;
for (perproperty in person) {
console.log(perproperty + ": " +
person[perproperty ]);
}
TypeScript While Loop
The while loop repeatedly executes a block of statements until a particular condition is true. It
first check the condition and executes a block of statements if condition is true.
Syntax:
while(condition){
//Block of statements
}
TypeScript while loop example:
var num:number=1;
while (num<=10) {
console.log(num);
nu
TypescriptBasics
M.Manikandan- MMK
TypeScript Do While Loop
The do while loop repeatedly executes a block of statements until a particular condition is
true. It first executes a block of statements and then check the condition.
Syntax:
do {
//Block of statements
}while(condition);
TypeScript do while loop example:
var num:number=1;
do{
console.log(num);
num++;
} while (num<=10);
TypeScript Function
A TypeScript function is a group of statements which is used for performing a specific task.
It provides the facility of code re-usability.
Typescript function declaration:
function function_name() {
// function body
}
Typescript function invocation:
function_name();
Typescript Function Example:
function hello() {
//function definition
console.log("Hello World!");
}
TypescriptBasics
M.Manikandan- MMK
hello();//function invocation
Typescript returning function
Typescript returning function syntax:
function function_name():return_type {
//block of statements
return value;
}
Typescript Returning Function Example:
function getMessage():string {
return "Hello World!";
}
function sayHello() {
var msg = getMessage();
console.log(msg);
}
sayHello();
Typescript parameterized function
Typescript parameterized function syntax:
function function_name( param1:datatype, ( param2:datatype) {
}
Typescript Parameterized Function Example:
function paramTest(rollNo:number,name:string) {
console.log(rollNo);
console.log(name);
}
paramTest(645,"Jai");
Typescript function optional parameter
Every parameter is assumed to be required by the function, in TypeScript. In short, the
number of parameters given to a function at function call has to match the number of
parameters in the function definition. We can mark a parameter optional by appending a
question mark to its name. Optional parameter should
be the last parameter of the function.
TypescriptBasics
M.Manikandan- MMK
Typescript function optional parameter syntax:
function function_name (param1:datatype, param2?:datatype)
Typescript function optional parameter example:
function dispDetails(fname:string,lname?:string) {
console.log("Fisrt Name",fname);
if(lname!=undefined)
console.log("Last Name",lname);
}
dispDetails("Asmita");
dispDetails("Nidhi", "Gupta");
Typescript rest parameters
When we talked about optional and default parameters all have one common thing, they talk
about one parameter at a time. Sometimes we need multiple parameters as a group.
TypeScript rest parameters used in such situations. They are act as the placeholder for
multiple arguments of the same type. Use the ellipsis (…) as the prefix of rest parameter.
Typescript rest parameters syntax:
function function_name (…param1:datatype)
Typescript rest parameters example:
function showNames(...names:string[]) {
for(var i = 0;i<names.length;i++) {
console.log(names[i]);
}
}
showNames("Rajeev","Gunjan","Vikram","Asmita");
showNames("Mahesh", "Jai", "Narender", "Vishal", "Hemant");
Typescript default parameters
The TypeScript default-initialized parameters are used to set a default value to the parameter
if the user does not provide one.
Note: We cannot declare a parameter optional and default at the same time.
TypescriptBasics
M.Manikandan- MMK
Typescript default parameters syntax:
function function_name(param1:datatype,param2:datatype = default_value)
Typescript default parameters example:
function displayDetails(name:string,sport:string = "Cricket") {
console.log("Name: " +name + ", Sport: "+ sport);
}
displayDetails("Jai");
displayDetails("Vivek","Football");
A function created without function name is known as anonymous function.
Typescript anonymous function syntax:
Typescript anonymous function syntax:
var result = function( [arguments] ) { ... }
Typescript anonymous function example:
var sayHello = function() {
return "Hello World!";
}
console.log(sayHello());
Typescript anonymous function with parameters example:
var sayHello = function(name:string) {
return "Hello "+name;
}
console.log(sayHello("Jai"));
Typescript function constructor
TypeScript provides the facility to create a function with the built-in JavaScript constructor
called Function ().
Typescript function constructor syntax:
var result = new Function( [arguments] ) { ... }
Typescript function constructor example:
var myFunction = new Function("num1", "num2", "return num1 + num2");
var result = myFunction(10, 15);
console.log(result);
TypescriptBasics
M.Manikandan- MMK
Arrow / Lambda function:
Typescript lambda or arrow functions are used to represent anonymous functions.
Parts of Arrow / Lambda function:
 Parameters
 Arrow notation/lambda notation (=>)
 Statements
Typescript Arrow / Lambda function syntax:
( [param1, parma2,…param n] )=>statement;
Typescript Arrow / Lambda function example:
var calculateSquare = (num:number)=> {
num = num * num;
console.log(num);
}
calculateSquare(10);
Ways to implement method overloading:
Method overloading means more than one methods with the same name but different
parameters. Parameters can be differing in types, numbers or order.
Ways to implement method overloading:
 Parameters differ in types.
function showDetails(s1:string):void;
function showDetails(num1:number):void;
 Parameters differ in number.
function showDetails(s1:string):void;
function showDetails(x:string, y:string):void;
 Parameters differ in order
function showDetails(num1:numer, s1:string):void;
function showDetails(s2:string, num2:number):void;
Typescript function overloading example:
function showDetails(name:string):void{
console.log(name);
}
TypescriptBasics
M.Manikandan- MMK
function showDetails(empId:number):void{
console.log(empId);
}
showDetails("Jai")
showDetails(123);
TypeScript Number Object
TypeScript number object:
The TypeScript Number object represents numerical data which can be integers or floating-
point numbers.
TypeScript number constants/properties:
Property Description
MAX_VALUE It specify the largest possible value.
MIN_VALUE It specify the smallest possible value.
NaN Equal to a value that is not a number.
NEGATIVE_INFINITY A value that is less than MIN_VALUE.
POSITIVE_INFINITY A value that is greater than MAX_VALUE
TypeScript number methods:
Methods Description
toExponential(fractionDigits)
It returns a string representing
the number object in exponential
notation.
TypescriptBasics
M.Manikandan- MMK
toFixed(digits)
It limits the number of digits after
decimal value.
toPrecision(digits)
It formats the number with given
number of digits.
toString() It converts number into string.
valueOf()
It converts other type of value into
number.
How to create TypeScript number object:
 By using number literals.
 By using Number() constructor.
By using number literals:
When we create a number literal browser automatically converts it to Number object.
Syntax:
var num1:number = value;
Example:
function numTest(num1:number):void{
console.log(num1);
}
numTest(123);
Try it:
By using Number() constructor:
We can create a TypeScript Number object by using Number() constructor. It returns NaN if
value is not a number.
Syntax:
var num1 = new Number(value);
Example:
TypescriptBasics
M.Manikandan- MMK
function numTest(num1:number):void{
console.log(num1);
}
var num1 = new Number(123);
var num2 = new Number("Hello");
numTest(num1);
numTest(num2);
TypeScript String Object Tutorial
TypeScript string object:
A TypeScript String object represents a sequence of characters.
TypeScript String Object Properties:
Property Description
constructor
It returns a reference to the String function that created the
object.
length It returns the length of the string.
prototype It allows us to add properties and methods to an object.
TypeScript String Object Methods:
Method Description
charAt() It returns the character at the specified index.
charCodeAt()
It returns a number indicating the Unicode value
of the character at the given index.
concat()
It combines the text of two strings and returns a
new string.
indexOf() It returns the index within the calling String
object of the first occurrence of the specified
TypescriptBasics
M.Manikandan- MMK
value, or -1 if not found.
lastIndexOf()
It returns the index within the calling String
object of the last occurrence of the specified
value, or -1 if not found.
localeCompare()
It returns a number indicating whether a
reference string comes before or after or is the
same as the given string in sort order.
match()
It is used to match a regular expression against a
string.
replace()
It is used to find a match between a regular
expression and a string, and to replace the
matched substring with a new substring.
search()
It executes the search for a match between a
regular expression and a specified string.
slice()
It extracts a section of a string and returns a new
string.
split()
It splits a String object into an array of strings
by separating the string into substrings.
substr()
It returns the characters in a string beginning at
the specified location through the specified
number of characters.
substring()
It 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.
TypescriptBasics
M.Manikandan- MMK
toLocaleUpperCase()
The characters within a string are converted to
upper case while respecting the current locale.
toLowerCase()
It returns the calling string value converted to
lower case.
toString()
It returns a string representing the specified
object.
toUpperCase()
It returns the calling string value converted to
uppercase.
valueOf()
It returns the primitive value of the specified
object.
How to create TypeScript string object:
 By using string literals.
 By using String() constructor.
By using number literals:
When we create a number literal browser automatically converts it to Number object.
Syntax:
var str1:string = “value”;
Example:
function stringTest(str:string):void{
console.log(str);
}
var str:string = "Sahdev";
stringTest(str);
Try it:
By using String() constructor:
We can create a TypeScript String object by using
String() constructor.
TypescriptBasics
M.Manikandan- MMK
Syntax:
var str1:string = new String(value);
Example:
function stringTest(str:string):void{
console.log(str);
}
var str:string = new String("Richi");
stringTest(str);
TypeScript Boolean Object
TypeScript boolean object:
A TypeScript Boolean object can represents two values “true” or “false”.
How to create TypeScript boolean object:
 By using boolean literals.
 By using Boolean() constructor.
Syntax:
Var b1:boolean = true;
var b2:boolean = new Boolean(value);
Example:
function booleanTest(bVar:boolean):void{
console.log(bVar.valueOf());
}
var boolean1:boolean=new Boolean(true);
var boolean2:boolean=new Boolean(false);
var boolean3:boolean=true;
booleanTest(boolean1);
booleanTest(boolean2);
booleanTest(boolean3);
TypescriptBasics
M.Manikandan- MMK
TypeScript Date Object Tutorial
TypeScript date object:
A TypeScript Date object represents a date. We can get or set year, month and day, hour,
minute, second, and millisecond fields of the object by Date methods.
TypeScript Date Object Properties:
Property Description
constructor It specifies the function that creates an object’s prototype.
prototype It allows us to add properties and methods to an object
TypeScript Date Object Methods:
Method Description
Date() It returns today’s date and time
getDate()
It returns the day of the month for the specified
date according to local time.
getDay()
It returns the day of the week for the specified
date according to local time.
getFullYear()
It returns the year of the specified date
according to local time.
getHours()
It returns the hour in the specified date
according to local time.
TypescriptBasics
M.Manikandan- MMK
getMilliseconds()
It returns the milliseconds in the specified date
according to local time.
getMinutes()
It returns the minutes in the specified date
according to local time.
getMonth()
It returns the month in the specified date
according to local time.
getSeconds()
It returns the seconds in the specified date
according to local time.
getTime()
It returns the numeric value of the specified
date as the number of milliseconds since
January 1, 1970, 00:00:00 UTC.
getTimezoneOffset()
It returns the time-zone offset in minutes for the
current locale.
getUTCDate()
It returns the day (date) of the month in the
specified date according to universal time.
getUTCDay()
It returns the day of the week in the specified
date according to universal time.
getUTCFullYear()
It returns the year in the specified date
according to universal time.
getUTCHours()
It returns the hours in the specified date
according to universal time.
getUTCMilliseconds()
It returns the milliseconds in the specified date
according to universal time.
getUTCMinutes()
It returns the minutes in the specified date
according to universal time.
TypescriptBasics
M.Manikandan- MMK
getUTCMonth()
It returns the month in the specified date
according to universal time.
getUTCSeconds()
It returns the seconds in the specified date
according to universal time.
getYear()
It returns the year in the specified date
according to local time. Use getFullYear
instead.
setDate()
It sets the day of the month for a specified date
according to local time.
setFullYear()
It sets the full year for a specified date
according to local time.
setHours()
It sets the hours for a specified date according
to local time.
setMilliseconds()
It sets the milliseconds for a specified date
according to local time.
setMinutes()
It sets the minutes for a specified date
according to local time.
setMonth()
It sets the month for a specified date according
to local time.
setSeconds()
It sets the seconds for a specified date
according to local time.
setTime()
It sets the Date object to the time represented
by a number of milliseconds since January 1,
1970, 00:00:00 UTC.
setUTCDate()
It sets the day of the month for a specified date
according to universal time.
TypescriptBasics
M.Manikandan- MMK
setUTCFullYear()
It sets the full year for a specified date
according to universal time.
setUTCHours()
It sets the hour for a specified date according to
universal time.
setUTCMilliseconds()
It sets the milliseconds for a specified date
according to universal time.
setUTCMinutes()
It sets the minutes for a specified date
according to universal time.
setUTCMonth()
It sets the month for a specified date according
to universal time.
setUTCSeconds()
It sets the seconds for a specified date
according to universal time.
setYear()
It sets the year for a specified date according to
local time. Use setFullYear instead.
toDateString()
It returns the “date” portion of the Date as a
human-readable string.
toGMTString()
It converts a date to a string, using the Internet
GMT conventions. Use toUTCString instead.
toLocaleDateString()
It returns the “date” portion of the Date as a
string, using the current locale’s conventions.
toLocaleFormat()
It converts a date to a string, using a format
string.
toLocaleString()
It converts a date to a string, using the current
locale’s conventions.
TypescriptBasics
M.Manikandan- MMK
toLocaleTimeString()
It returns the “time” portion of the Date as a
string, using the current locale’s conventions.
toSource()
It returns a string representing the source for an
equivalent Date object; you can use this value
to create a new object.
toString()
It returns a string representing the specified
Date object.
toTimeString()
It returns the “time” portion of the Date as a
human-readable string.
toUTCString()
It converts a date to a string, using the universal
time convention.
valueOf() It returns the primitive value of a Date object.
TypeScript Date Object Methods:
Method Description
Date.parse()
Parses a string representation of a date and time and
returns the internal millisecond representation of that
date.
Date.UTC()
It returns the millisecond representation of the specified
UTC date and time.
How to create TypeScript date object:
 new Date()
 new Date(milliseconds)
 new Date(datestring)
TypescriptBasics
M.Manikandan- MMK
 new Date(year,month,date[,hour,minute,second,millisecond ])
Example:
function dateTest(date:Date):void{
var hours=date.getHours();
var minutes=date.getMinutes();
var seconds=date.getSeconds();
console.log("Current Time: "+hours+":"+minutes+":"+seconds);
}
var date=new Date();
dateTest(date);
TypeScript Math Object
TypeScript math object:
A TypeScript Math object provides no. of properties and methods for performing
mathematical operations. Math is not a constructor and all the properties and methods of
Math are static.
TypeScript Math Object Properties:
Property Description
E 
Euler’s constant and the base of natural logarithms,
approximately 2.718.
LN2 Natural logarithm of 2, approximately 0.693.
LN10 Natural logarithm of 10, approximately 2.302.
LOG2E Base 2 logarithm of E, approximately 1.442.
LOG10E Base 10 logarithm of E, approximately 0.434.
PI
Ratio of the circumference of a circle to its diameter,
approximately 3.14159.
TypescriptBasics
M.Manikandan- MMK
SQRT1_2
Square root of 1/2; equivalently, 1 over the square root of 2,
approximately 0.707.
SQRT2 Square root of 2, approximately 1.414.
TypeScript Math Object Methods:
Method Description
abs() It returns the absolute value of a number.
acos() It returns the arccosine (in radians) of a number.
asin() It returns the arcsine (in radians) of a number.
atan() It returns the arctangent (in radians) of a number.
atan2() It returns the arctangent of the quotient of its arguments.
ceil()
It returns the smallest integer greater than or equal to a
number.
cos() It returns the cosine of a number.
exp()
It returns EN, where N is the argument, and E is Euler’s
constant, the base of the natural logarithm.
floor() It returns the largest integer less than or equal to a number.
log() It returns the natural logarithm (base E) of a number.
max() It returns the largest of zero or more numbers.
min() It returns the smallest of zero or more numbers.
TypescriptBasics
M.Manikandan- MMK
pow()
It returns base to the exponent power, that is, base
exponent.
random() It returns a pseudo-random number between 0 and 1.
round()
It returns the value of a number rounded to the nearest
integer.
sin() It returns the sine of a number.
sqrt() It returns the square root of a number.
tan() It returns the tangent of a number.
toSource() It returns the string “Math”.
Example:
function mathTest(num:number):void{
var squarRoot = Math.sqrt(num);
console.log("Random Number: " + num);
console.log("Square root: " + squarRoot);
}
var num:number = Math.random();
mathTest(num);
TypeScript Array Object
TypeScript array object:
A TypeScript Array object represents a collection of elements of the same type.
TypeScript Array Object Properties:
Property Description
TypescriptBasics
M.Manikandan- MMK
constructor
Returns a reference to the array function that created the
object.
length It reflects the number of elements in an array.
prototype It allows us to add properties and methods to an object.
TypeScript Array Object Methods:
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.
forEach() Calls a function for each element in the array.
indexOf()
Returns the first (least) index of an element within the
array equal to the specified value, or -1 if none is found.
join() Joins all elements of an array into a string.
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.
TypescriptBasics
M.Manikandan- MMK
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.
slice() Extracts a section of an array and returns a new array.
some()
Returns true if at least one element in this array satisfies
the provided testing function.
toSource() Represents the source code of an object
sort() Represents the source code of an object
splice() Adds and/or removes elements from an array.
toString() Returns a string representing the array and its elements.
unshift()
Adds one or more elements to the front of an array and
returns the new length of the array.
How to create TypeScript array object:
 By using array literals.
TypescriptBasics
M.Manikandan- MMK
 By using Array() constructor.
By using array literals:
Using an array literal is the simplest way to create a TypeScript Array.
Syntax:
var array1:string[] = ["element1","element2","elementN"];
Example:
function arrayTest(names:string):void{
for (i=0;i<names.length;i++){
console.log(names[i]);
}
}
var names:string[] = ["Bharat","Sahdev","Richi","Harish","Bharti","Deepika","Shaveta"];
arrayTest(names);
By using Array() constructor:
We can create a TypeScript Array object by using Array() constructor.
Syntax:
var array1 = new Array(“element1”, “element2”, “elementN”);
Example:
function arrayTest(names:string):void{
for (i=0;i<names.length;i++){
console.log(names[i]);
}
}
var names:string[] = new Array("Jai","Vivek","Mahesh","Narender","Vishal","Hemant");
arrayTest(names);
TypeScript Tuple
TypeScript tuples:
Typescript tuple represents a heterogeneous collection
of values i.e. it contains a collection of values of
TypescriptBasics
M.Manikandan- MMK
different types.
Syntax:
var tupleName = [value1,value2,value3,…valuen]
Example:
function tupleTest(values):void{
for (i=0;i<values.length;i++){
console.log(values[i]);
}
}
var values = [10,20,"Gunjan","Rajeev","Vikram","Sudhir"];
tupleTest(values);
TypeScript Union Type
TypeScript union type:
TypeScript Union Type provides the facility to combine one or two types for a variable. The
pipe symbol (|) is used to combine the two or more data types.
Syntax:
var varName: dataType1|dataType2|dataType3
Example:
function unionTest(value:string|number):void{
console.log(value);
}
unionTest("Jai");
unionTest(123);
Typescript Interface T
Dictionary meaning of interface:
A point where two systems, subjects, organizations, etc., meet and interact.
TypeScript interface:
TypescriptBasics
M.Manikandan- MMK
An interface is declared with interface keyword. It is a way of implementing 100%
abstraction. It only contains the declaration of the members. Interface forms a contract with
your class that force your class to have all methods defined by the interface must appear in
the class.
Syntax:
interface interface_name {
}
Example:
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
var customer:IPerson = {
firstName:"Ajay",
lastName:"Laddha",
sayHi: ():string =>{return "Hi"}
}
console.log("Customer Object Details: ");
console.log(customer.sayHi());
console.log(customer.firstName);
console.log(customer.lastName);
var employee:IPerson = {
firstName:"Vikas",
lastName:"Jainer",
sayHi: ():string =>{return "Hello"}
}
console.log("Employee Object Details: ");
console.log(employee.sayHi());
console.log(employee.firstName);
console.log(employee.lastName);
TypescriptBasics
M.Manikandan- MMK
Typescript Class
TypeScript Class:
As we discussed in earlier tutorials that TypeScript supports object-oriented programming
concepts like classes, interfaces, etc. Class acts as a blue print or template for creating
objects. It provides state and behaviour for its objects. A class is used to encapsulate the data
for the object.
Syntax:
class class_name {
//field
//constructor
//function
}
Typescript creating objects:
The new keyword followed by the class name is used to create an instance of the class.
var objectName = new className([ arguments ])
Example:
class Employee {
//field
name:string;
//constructor
constructor(name:string) {
this.name = name;
}
//function
display():void {
console.log("Employee Name: "+this.name);
}
}
//create an object
TypescriptBasics
M.Manikandan- MMK
var obj = new Employee("Jai");
//access the field
console.log("Employee Name: "+obj.name);
//access the function
obj.display();
TypeScript Abstract Class
TypeScript Abstract Class:
Abstract class is a way of implementing 0 to 100% abstraction. A class declared with abstract
keyword is known as an abstract class. An abstract class may or may not contain abstract
method. Abstract classes cannot be instantiated.
Syntax:
abstract class className {
// declare fields
// declare abstract/non-abstract methods
}
Abstract method:
A method with no implementation i.e. without braces and followed by a semicolon.
Syntax:
abstract return_type methodName();
Example:
abstract class Department {
constructor(public name: string) {
}
printName(): void {
console.log("Department name: " + this.name);
}
TypescriptBasics
M.Manikandan- MMK
abstract printMeeting(): void;
}
class AccountingDepartment extends Department {
constructor() {
super("Accounting and Auditing");
}
printMeeting(): void {
console.log("The Accounting Department meets each Monday at 10am.");
}
generateReports(): void {
console.log("Generating accounting reports...");
}
}
let department: Department;
department = new AccountingDepartment();
department.printName();
department.printMeeting();
Typescript Object
TypeScript Object:
A real world entity is known as an object. Like every real world object, software objects also
have state and behavior. State of the object is represented by data members or fields and
behavior is represented by methods.
In TypeScript an object represents an instance which contains set of key value pairs. The
values can be scalar values, functions or array of other objects.
Syntax:
var objectName = {
key1: “value”, //scalar value
key2: function() {
TypescriptBasics
M.Manikandan- MMK
//functions
},
Key3:[“content1”, “content2”] //collection
};
Example:
class Employee {
//field
name:string;
empId:string;
}
//function
var display = function(obj: {name:string, empId:string}) {
console.log("Employee Name: "+obj.name);
console.log("Employee EmpId: "+obj.empId);
}
//create an object
var obj:Employee = {name:"Jai", empId:"EMP024"};
//access the function
display(obj);
Typescript Duck Typing
TypeScript duck typing:
Duck-typing is a powerful feature which brings strong typing concepts in TypeScript code.
TypeScript provides the duck typing type-checking which focus on the shape that values
have. It checks for the presence of certain properties in the objects instead of the actual object
type.
The following example does not allow substitution of a Parrot for a Duck, because the Duck
class has an additional method (so Parrot fails
duck typing). Sparrows and Parrots are apparently
substitutable in duck typing because there’s nothing a
TypescriptBasics
M.Manikandan- MMK
parrot can do that a sparrow cannot, and vice versa. Of course, a Duck can substitute for a
Parrot, because if it sounds like a parrot, it is a parrot.
Example:
class Sparrow {
sound = "cheep";
}
class Parrot {
sound = "squawk";
}
class Duck {
sound = "quack";
swim(){
console.log("Going for a dip!");
}
}
var parrot: Parrot = new Sparrow(); // substitutes
var sparrow: Sparrow = new Parrot(); // substitutes
var parrotTwo: Parrot = new Duck();
//var duck: Duck = new Parrot(); // IDE & compiler error
console.log("Parrot says: "+parrot.sound);
console.log("sparrow says: "+sparrow.sound);
console.log("parrot says: "+parrotTwo.sound);
TypeScript Namespaces
TypeScript NameSpace:
TypeScript namespace is a way to organize your code. Internal modules in typescript are now
referred to namespaces. The namespace keyword is used to define a namespace.
Syntax:
namespace NameSpaceName {
export interface IInterfaceName { }
export class ClassName { }
}
TypescriptBasics
M.Manikandan- MMK
Access the class or interface in another namespace:
NameSpaceName.ClassName;
Example:
namespace Validation {
export interface StringValidator {
isValid(s: string): boolean;
}
const lettersRegexp = /^[A-Za-z]+$/;
const numberRegexp = /^[0-9]+$/;
export class LettersOnlyValidator implements StringValidator {
isValid(s: string) {
return lettersRegexp.test(s);
}
}
export class ZipCodeValidator implements StringValidator {
isValid(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
}
//Some samples to try
let strings = ["You", "53454", "Hello"];
// Validators to use
let validators: { [s: string]: Validation.StringValidator; } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();
//Show whether each string passed each validator
for (let s of strings) {
for (let name in validators) {
console.log(`"${ s }" - ${ validators[name].isValid(s) ? "Valid" : "Invalid" } ${ name
}`);
}
}
TypescriptBasics
M.Manikandan- MMK
TypeScript Multi-file namespaces:
We can split the namespace into multiple files. As these multiple files will have dependencies
we have to add reference tag to tell the compiler about the relationships between the files.
/// <reference path = "FileName.ts" />
Example:
Validation.ts
namespace Validation {
export interface StringValidator {
isValid (s: string): boolean;
}
}
LettersValidator.ts
/// <reference path="Validation.ts" />
namespace Validation {
const lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements StringValidator {
isValid (s: string) {
return lettersRegexp.test(s);
}
}
}
ZipCodeValidator.ts
/// <reference path="Validation.ts" />
namespace Validation {
const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isValid (s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
}
Test.ts
TypescriptBasics
M.Manikandan- MMK
/// <reference path="Validation.ts" />
/// <reference path="LettersValidator.ts" />
/// <reference path="ZipCodeValidator.ts" />
//Some samples to try
let strings = ["You", "53454", "Hello"];
// Validators to use
let validators: { [s: string]: Validation.StringValidator; } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();
//Show whether each string passed each validator
for (let s of strings) {
for (let name in validators) {
console.log(`"${ s }" - ${ validators[name].isValid(s) ? "Valid" : "Invalid" } ${ name
}`);
}
}
TypeScript Module
TypeScript module:
A module refers to a set of standardized parts or independent units that can be used to
construct a more complex structure. TypeScript modules provides a way to organize the code
for better reuse.
Syntax:
export interface InterfaceName {
//Block of statements
}
The import keyword is used to use the declared module in another file.
import testInterfaceRef = require(“./InterfaceName”);
Example:
IShowDetails.ts
TypescriptBasics
M.Manikandan- MMK
export interface IShowDetails {
display();
}
Student.ts
import showDetails = require("./IShowDetails");
export class Student implements showDetails.IShowDetails {
public display() {
console.log("Student Details");
}
}
Teacher.ts
import showDetails = require("./IShowDetails");
export class Teacher implements showDetails.IShowDetails {
public display() {
console.log("Teacher details.");
}
}
TestShape.ts
import showDetails = require("./IShowDetails");
import student = require("./Student");
import teacher = require("./Teacher");
function showAllDetails(detailsToShow: showDetails.IShowDetails) {
detailsToShow.display();
}
showAllDetails(new student.Student());
showAllDetails(new teacher.Teacher());
TypeScript Ambient Module
TypeScript ambient module:
As we discussed in earlier tutorials TypeScript provides the facility to safely and easily use
existing JavaScript libraries like jquery, angularjs, nodejs etc. Ambient declarations allow us
to safely use existing popular JavaScript libraries.
Ambient declaration files are savedwith .d.ts
extension.
TypescriptBasics
M.Manikandan- MMK
Syntax to declare ambient variables or modules:
declare module ModuleName {
}
Syntax to use Ambient files:
/// <reference path = "AmbientFileName.d.ts" />
Example:
Let us consider that we are using a third party js library with following code.
CalcSum.js
var TestVar;
(function (TestVar) {
var Calc = (function () {
function Calc() {
}
Calc.prototype.doSum = function (num1, num2) {
return num1 + num2;
}
}
}
As this is a js file and we still want to use the doSum() function in our TypeScript code with
type safety. We can use this by using ambient declaration. Let us create an ambient
declaration file.
Calc.d.ts
declare module TestVar {
export class Calc {
doSum(num1:number, num2:number) : number;
}
}
Now we have to include the above ambient declaration into our typescript file.
CalcTest.ts
/// <reference path = "Calc.d.ts" />
var obj = new TestVar.Calc();
console.log(obj.doSum(10,20));

More Related Content

PDF
TypeScript
Merchu Liang
 
PPT
Docker introduction
Phuc Nguyen
 
PDF
Kubernetes Introduction
Peng Xiao
 
PPTX
CQRS: Command/Query Responsibility Segregation
Brian Ritchie
 
PDF
Introduction to Docker storage, volume and image
ejlp12
 
PDF
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...
Edureka!
 
PDF
Introduction to container based virtualization with docker
Bangladesh Network Operators Group
 
PDF
Docker swarm
Alberto Guimarães Viana
 
TypeScript
Merchu Liang
 
Docker introduction
Phuc Nguyen
 
Kubernetes Introduction
Peng Xiao
 
CQRS: Command/Query Responsibility Segregation
Brian Ritchie
 
Introduction to Docker storage, volume and image
ejlp12
 
What is Docker | Docker Tutorial for Beginners | Docker Container | DevOps To...
Edureka!
 
Introduction to container based virtualization with docker
Bangladesh Network Operators Group
 

What's hot (20)

PPTX
Introduction to kubernetes
Rishabh Indoria
 
PPTX
Dependency injection ppt
Swati Srivastava
 
PDF
Kubernetes Docker Container Implementation Ppt PowerPoint Presentation Slide ...
SlideTeam
 
PDF
Docker swarm introduction
Evan Lin
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PDF
Angular Observables & RxJS Introduction
Rahat Khanna a.k.a mAppMechanic
 
PPTX
Introduction to Distributed Tracing
petabridge
 
PPTX
Introducing type script
Remo Jansen
 
PPSX
Containers Docker Kind Kubernetes Istio
Araf Karsh Hamid
 
PDF
Kubernetes Architecture - beyond a black box - Part 1
Hao H. Zhang
 
PPTX
Type script - advanced usage and practices
Iwan van der Kleijn
 
PPTX
android studio
Lahore Garrison University
 
PPTX
What is Docker
Pavel Klimiankou
 
PDF
The Need of Cloud-Native Application
Emiliano Pecis
 
PDF
Introduction to React JS
Bethmi Gunasekara
 
PDF
Terraform introduction
Jason Vance
 
PDF
Istio Service Mesh for Developers and Platform Engineers
SaiLinnThu2
 
PDF
DevSecOps
Spv Reddy
 
PDF
Advanced Terraform
Samsung Electronics
 
PDF
TypeScript Best Practices
felixbillon
 
Introduction to kubernetes
Rishabh Indoria
 
Dependency injection ppt
Swati Srivastava
 
Kubernetes Docker Container Implementation Ppt PowerPoint Presentation Slide ...
SlideTeam
 
Docker swarm introduction
Evan Lin
 
TypeScript Introduction
Dmitry Sheiko
 
Angular Observables & RxJS Introduction
Rahat Khanna a.k.a mAppMechanic
 
Introduction to Distributed Tracing
petabridge
 
Introducing type script
Remo Jansen
 
Containers Docker Kind Kubernetes Istio
Araf Karsh Hamid
 
Kubernetes Architecture - beyond a black box - Part 1
Hao H. Zhang
 
Type script - advanced usage and practices
Iwan van der Kleijn
 
What is Docker
Pavel Klimiankou
 
The Need of Cloud-Native Application
Emiliano Pecis
 
Introduction to React JS
Bethmi Gunasekara
 
Terraform introduction
Jason Vance
 
Istio Service Mesh for Developers and Platform Engineers
SaiLinnThu2
 
DevSecOps
Spv Reddy
 
Advanced Terraform
Samsung Electronics
 
TypeScript Best Practices
felixbillon
 
Ad

Similar to Typescript Basics (20)

PDF
TYPESCRIPT.pdfgshshhsjajajsjsjjsjajajjajjj
sonidsxyz02
 
PPTX
Complete Notes on Angular 2 and TypeScript
EPAM Systems
 
PDF
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
TypeScript Overview
Aniruddha Chakrabarti
 
PPTX
typescript.pptx
ZeynepOtu
 
PPTX
Typescript language extension of java script
michaelaaron25322
 
PDF
Type script
srinivaskapa1
 
PPTX
Typescript
Nikhil Thomas
 
PPTX
Type script
Mallikarjuna G D
 
PDF
Reasons to Use Typescript for Your Next Project Over Javascript.pdf
MobMaxime
 
PPTX
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
 
PPTX
TypeScript: Basic Features and Compilation Guide
Nascenia IT
 
PDF
Introduction to TypeScript
NexThoughts Technologies
 
PPTX
002. Introducere in type script
Dmitrii Stoian
 
PPTX
TypeScript
Udaiappa Ramachandran
 
ODP
Getting started with typescript and angular 2
Knoldus Inc.
 
PPTX
Typescript-7 (1).pptx
SachinSonawane100
 
PPTX
Typescript: Beginner to Advanced
Talentica Software
 
PDF
Introduction to TypeScript by Winston Levi
Winston Levi
 
PPT
Learning typescript
Alexandre Marreiros
 
TYPESCRIPT.pdfgshshhsjajajsjsjjsjajajjajjj
sonidsxyz02
 
Complete Notes on Angular 2 and TypeScript
EPAM Systems
 
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
TypeScript Overview
Aniruddha Chakrabarti
 
typescript.pptx
ZeynepOtu
 
Typescript language extension of java script
michaelaaron25322
 
Type script
srinivaskapa1
 
Typescript
Nikhil Thomas
 
Type script
Mallikarjuna G D
 
Reasons to Use Typescript for Your Next Project Over Javascript.pdf
MobMaxime
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
 
TypeScript: Basic Features and Compilation Guide
Nascenia IT
 
Introduction to TypeScript
NexThoughts Technologies
 
002. Introducere in type script
Dmitrii Stoian
 
Getting started with typescript and angular 2
Knoldus Inc.
 
Typescript-7 (1).pptx
SachinSonawane100
 
Typescript: Beginner to Advanced
Talentica Software
 
Introduction to TypeScript by Winston Levi
Winston Levi
 
Learning typescript
Alexandre Marreiros
 
Ad

Recently uploaded (20)

PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PDF
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
Landforms and landscapes data surprise preview
jpinnuck
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 

Typescript Basics

  • 1. TypescriptBasics M.Manikandan- MMK TypeScript TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code. TypeScript doesn’t run in the browser. The code written in typescript is compiled to JavaScript, which then runs in the browser. TypeScript is open source. It was designed by Anders Hejlsberg (the lead architect of C#) at Microsoft. Features of TypeScript: 1. The code written in typescript is compiled to the JavaScript for the purpose of execution. 2. As we already discussed that the code written in typescript is compiled to the JavaScript which can reuse all of the existing JavaScript frameworks, tools, and libraries. 3. As TypeScript is a superset of JavaScript so any valid .js file can be renamed to .ts and compiled with other TypeScript files. 4. TypeScript is portable i.e. it can run on any environment that JavaScript runs on. 5. TypeScript provides optional static typing. JavaScript is dynamically typed. This means JavaScript does not know what type a variable is until it actsually instantiated at run-time. This also means that it may be too late. TypeScript adds type support to JavaScript. TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. For example: var msg = “hello” in TypeScript is the same as var msg : string = “hello”. TLS (TypeScript Language Service) provides the facility to identify the type of the variable based on its value if it is declared with no type. 6. TypeScript supports Object Oriented Programming concepts like classes, object, interfaces and inheritance etc. 7. TypeScript Definition file with .d.ts extension provides definition for external JavaScript libraries. 8. TypeScript provides strict null checks. TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type. For example, let num1 : number = undefined will result in a compile error. This fits perfectly with type theory, since undefined is not a number. One can define x to be a sum type of number and undefined to correct this: let num1 : number | undefined = undefined.
  • 2. TypescriptBasics M.Manikandan- MMK JavaScript: JavaScript is the most popular programming language. It is lightweight and commonly used to create interactive and dynamic web pages. It is developed by Netscape in 1995 and named as LiveScript which is later renamed to JavaScript. Read more on JavaScript. TypeScript: TypeScript: TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code. Differences betweenjavascriptand typescript: Javascript Typescript JavaScript is a scripting language. TypeScript supports object oriented programming language concepts. There is no static typing. ex: var num. TypeScript supports optional static typing JavaScript doesn’t supports interfaces. TypeScript supports interfaces. JavaScript has no optional parameter feature. TypeScript has optional parameter feature. JavaScript doesn’t supports generics. TypeScript Supports generics. JavaScript doesn’t have modules support. Number, string etc. are the objects. TypeScript supports modules . Number, string etc. are the interfaces. Difference Between Var And Let var keyword: The var statement is used to declare a variable. We can
  • 3. TypescriptBasics M.Manikandan- MMK optionally initialize the value of that variable. Example: var num =10; let keyword: The let statement is used to declare a local variable in a block scope. It is similar to var, in that we can optionally initialize the variable. Example: let num =10; Scope difference between var and let: Var scope: The var is scoped to the nearest function block. In the below example variable num2 is declared within a block but can be accessed within the function and outside this block. The statement in which we are using this variable should be after this block which means we cannot access num2 before the declaration statement. function varTest(){ var num1 =10; console.log(num1); //output 10 if(true){ var num2=20; console.log(num2); //output 20 } console.log(num1); //output 10 console.log(num2); //output 20 } Let scope: The let is scoped to the nearest enclosing block. In the below example variable num2 is declared within a block and cannot be accessed outside this block. function letTest(){ var num1 =10; console.log(num1); //output 10 if(true){ var num2=20; console.log(num2); //output 20 } console.log(num1); //output 10 console.log(num2); //Cannot be accessed here
  • 4. TypescriptBasics M.Manikandan- MMK } Redeclaration difference between var and let: Redeclarationwith var: The var keyword provides the facility to re-declare the same variable in the same scope. function varTest(){ var num1 = 10; var num1 = 20; //num1 is replaced } Redeclaration with let: The let keyword does not provides the facility to re-declare the same variable in the same scope. function letTest(){ var num1 = 10; var num1 = 20; // SyntaxError: Identifier num1 has already been declared } Typescript Hello World Let us start TypeScript programming with simple “Hello World!” example. Create and save the file with .ts extension. In first line we declare a variable of string type. In second line we display the variable’s value at the terminal window. TypeScript Hello World: var message:string = "Hello World!" ; console.log(message); As we discussed in earlier tutorials that TypeScript code will be converted into JavaScript Code. After the compilation of above TypeScript code following JavaScript code will be generated. Translatedcode: var message = "Hello World!"; console.log(message); Compile and Execute a TypeScript Program: Comiple: Use below command on the terminal window for compilation. tsc typeScriptFileName.ts Note − Multiple files can be compiled at once. tsc typeScriptFileName1.ts, typeScriptFileName2.ts, typeScriptFileName3.ts Execute: Use below command on the terminal
  • 5. TypescriptBasics M.Manikandan- MMK window for execution. node typeScriptFileName.js
  • 6. TypescriptBasics M.Manikandan- MMK The let keyword does not provides the facility to re-declare the same variable in the same scope. TypeScript Data Types System When a variable is declared some part of memory is reserved. But how much memory will be reserved. It depends upon the data type of the variable. i.e. how much memory will be reserved and which type of data can be stored in reserved memory is depends upon data type of the variable. The Type System of a language represents these data types. Data types in TypeScript: 1. Any Type: represents the super type of all data types in TypeScript. TypeScript provides the compile time data type-checking for the variables. In some situation we may not know what type of value for variable will come. These values may come from dynamic content e.g. from the user. In such cases, we want to opt-out of type-checking and let the values pass through compile-time checks. The any type is used for these variables. 2. Built-in types: Data type Keyword Description Number number It represents a double precision 64-bit floating point values which can be used to represent both integers and fractions. String string It represents a sequence of characters. Boolean boolean It represents logical values true and false. Void void It is used on function return types to represent non-returning functions. Null null It is used to represent an intentional absence of an object value. Undefined undefined It represents uninitialized variables. 3. User-defined types: include Enumerations (enums), classes, interfaces, arrays, and tuple. Variables In Typescript Variable is the name of reserved memory location. It means when we declare a variable some part of memory is reserved. Rules for declaring a TypeScript variable: 1. TypeScript variable name must begin with a letter, underscore, or dollar sign. 2. TypeScript variable names are case sensitive. 3. TypeScript reserved keywords like abstract, boolean etc can’t be used as TypeScript variable name. Variable Declaration in TypeScript
  • 7. TypescriptBasics M.Manikandan- MMK TypeScript Switch Statement TypeScript switch statement is used to execute a block of statement based on the switch expression value. It is like if else if statement. Syntax: switch(expression){ case value1: //TypeScript block of statements break; case value2: //TypeScript block of statements break; ... default: //TypeScript block of statements break; } TypeScript Switch Statement Example: var today:string; switch (new Date().getDay()) { case 0: today = "Sunday"; break; case 1: today = "Monday"; break; case 2: today = "Tuesday"; break; case 3:
  • 8. TypescriptBasics M.Manikandan- MMK today = "Wednesday"; break; case 4: today = "Thursday"; break; case 5: today = "Friday"; break; case 6: today = "Saturday"; } console.log("Today is "+ today); TypeScript For Loop The for loop repeatedly executes a block of statements until a particular condition is true. Syntax: for(initialization; condition; statement){ //Block of statements } Where: initialization statement: is used to initialize the loop variable. boolean expression: is used for condition check whether returns true or false. statement: is used for either increment or decrements the loop variable. TypeScript for loop example: for (num=1; num<=10; num++) { console.log(num); } Break Statement: The break statement is a control statement which is used to jump out of the loop. Syntax:
  • 9. TypescriptBasics M.Manikandan- MMK for( initialization; condition; statement){ //Block of statements if(condition){ break; } } Typescript for loop break example: for (num=1; num<=10; num++) { if(num==6){ break; } console.log(num); } Continue statement: The continue statement is a control statement which is used to skip the following statement in the body of the loop and continue with the next iteration of the loop. Syntax: for( initialization; condition; statement){ //Block of statements if(condition){ continue; } } TypeScript for loop continue example: for (num=1; num<=10; num++) { if(num==6){ continue; } console.log(num); }
  • 10. TypescriptBasics M.Manikandan- MMK TypeScript For In Loop The for in loop is used to iterate the properties of an object. Syntax: for(property in object){ //Block of statements } TypeScript for in loop example: var person = {Fname:"Rajeev", Lname:"Johari", Age:40}; var perproperty; for (perproperty in person) { console.log(perproperty + ": " + person[perproperty ]); } TypeScript While Loop The while loop repeatedly executes a block of statements until a particular condition is true. It first check the condition and executes a block of statements if condition is true. Syntax: while(condition){ //Block of statements } TypeScript while loop example: var num:number=1; while (num<=10) { console.log(num); nu
  • 11. TypescriptBasics M.Manikandan- MMK TypeScript Do While Loop The do while loop repeatedly executes a block of statements until a particular condition is true. It first executes a block of statements and then check the condition. Syntax: do { //Block of statements }while(condition); TypeScript do while loop example: var num:number=1; do{ console.log(num); num++; } while (num<=10); TypeScript Function A TypeScript function is a group of statements which is used for performing a specific task. It provides the facility of code re-usability. Typescript function declaration: function function_name() { // function body } Typescript function invocation: function_name(); Typescript Function Example: function hello() { //function definition console.log("Hello World!"); }
  • 12. TypescriptBasics M.Manikandan- MMK hello();//function invocation Typescript returning function Typescript returning function syntax: function function_name():return_type { //block of statements return value; } Typescript Returning Function Example: function getMessage():string { return "Hello World!"; } function sayHello() { var msg = getMessage(); console.log(msg); } sayHello(); Typescript parameterized function Typescript parameterized function syntax: function function_name( param1:datatype, ( param2:datatype) { } Typescript Parameterized Function Example: function paramTest(rollNo:number,name:string) { console.log(rollNo); console.log(name); } paramTest(645,"Jai"); Typescript function optional parameter Every parameter is assumed to be required by the function, in TypeScript. In short, the number of parameters given to a function at function call has to match the number of parameters in the function definition. We can mark a parameter optional by appending a question mark to its name. Optional parameter should be the last parameter of the function.
  • 13. TypescriptBasics M.Manikandan- MMK Typescript function optional parameter syntax: function function_name (param1:datatype, param2?:datatype) Typescript function optional parameter example: function dispDetails(fname:string,lname?:string) { console.log("Fisrt Name",fname); if(lname!=undefined) console.log("Last Name",lname); } dispDetails("Asmita"); dispDetails("Nidhi", "Gupta"); Typescript rest parameters When we talked about optional and default parameters all have one common thing, they talk about one parameter at a time. Sometimes we need multiple parameters as a group. TypeScript rest parameters used in such situations. They are act as the placeholder for multiple arguments of the same type. Use the ellipsis (…) as the prefix of rest parameter. Typescript rest parameters syntax: function function_name (…param1:datatype) Typescript rest parameters example: function showNames(...names:string[]) { for(var i = 0;i<names.length;i++) { console.log(names[i]); } } showNames("Rajeev","Gunjan","Vikram","Asmita"); showNames("Mahesh", "Jai", "Narender", "Vishal", "Hemant"); Typescript default parameters The TypeScript default-initialized parameters are used to set a default value to the parameter if the user does not provide one. Note: We cannot declare a parameter optional and default at the same time.
  • 14. TypescriptBasics M.Manikandan- MMK Typescript default parameters syntax: function function_name(param1:datatype,param2:datatype = default_value) Typescript default parameters example: function displayDetails(name:string,sport:string = "Cricket") { console.log("Name: " +name + ", Sport: "+ sport); } displayDetails("Jai"); displayDetails("Vivek","Football"); A function created without function name is known as anonymous function. Typescript anonymous function syntax: Typescript anonymous function syntax: var result = function( [arguments] ) { ... } Typescript anonymous function example: var sayHello = function() { return "Hello World!"; } console.log(sayHello()); Typescript anonymous function with parameters example: var sayHello = function(name:string) { return "Hello "+name; } console.log(sayHello("Jai")); Typescript function constructor TypeScript provides the facility to create a function with the built-in JavaScript constructor called Function (). Typescript function constructor syntax: var result = new Function( [arguments] ) { ... } Typescript function constructor example: var myFunction = new Function("num1", "num2", "return num1 + num2"); var result = myFunction(10, 15); console.log(result);
  • 15. TypescriptBasics M.Manikandan- MMK Arrow / Lambda function: Typescript lambda or arrow functions are used to represent anonymous functions. Parts of Arrow / Lambda function:  Parameters  Arrow notation/lambda notation (=>)  Statements Typescript Arrow / Lambda function syntax: ( [param1, parma2,…param n] )=>statement; Typescript Arrow / Lambda function example: var calculateSquare = (num:number)=> { num = num * num; console.log(num); } calculateSquare(10); Ways to implement method overloading: Method overloading means more than one methods with the same name but different parameters. Parameters can be differing in types, numbers or order. Ways to implement method overloading:  Parameters differ in types. function showDetails(s1:string):void; function showDetails(num1:number):void;  Parameters differ in number. function showDetails(s1:string):void; function showDetails(x:string, y:string):void;  Parameters differ in order function showDetails(num1:numer, s1:string):void; function showDetails(s2:string, num2:number):void; Typescript function overloading example: function showDetails(name:string):void{ console.log(name); }
  • 16. TypescriptBasics M.Manikandan- MMK function showDetails(empId:number):void{ console.log(empId); } showDetails("Jai") showDetails(123); TypeScript Number Object TypeScript number object: The TypeScript Number object represents numerical data which can be integers or floating- point numbers. TypeScript number constants/properties: Property Description MAX_VALUE It specify the largest possible value. MIN_VALUE It specify the smallest possible value. NaN Equal to a value that is not a number. NEGATIVE_INFINITY A value that is less than MIN_VALUE. POSITIVE_INFINITY A value that is greater than MAX_VALUE TypeScript number methods: Methods Description toExponential(fractionDigits) It returns a string representing the number object in exponential notation.
  • 17. TypescriptBasics M.Manikandan- MMK toFixed(digits) It limits the number of digits after decimal value. toPrecision(digits) It formats the number with given number of digits. toString() It converts number into string. valueOf() It converts other type of value into number. How to create TypeScript number object:  By using number literals.  By using Number() constructor. By using number literals: When we create a number literal browser automatically converts it to Number object. Syntax: var num1:number = value; Example: function numTest(num1:number):void{ console.log(num1); } numTest(123); Try it: By using Number() constructor: We can create a TypeScript Number object by using Number() constructor. It returns NaN if value is not a number. Syntax: var num1 = new Number(value); Example:
  • 18. TypescriptBasics M.Manikandan- MMK function numTest(num1:number):void{ console.log(num1); } var num1 = new Number(123); var num2 = new Number("Hello"); numTest(num1); numTest(num2); TypeScript String Object Tutorial TypeScript string object: A TypeScript String object represents a sequence of characters. TypeScript String Object Properties: Property Description constructor It returns a reference to the String function that created the object. length It returns the length of the string. prototype It allows us to add properties and methods to an object. TypeScript String Object Methods: Method Description charAt() It returns the character at the specified index. charCodeAt() It returns a number indicating the Unicode value of the character at the given index. concat() It combines the text of two strings and returns a new string. indexOf() It returns the index within the calling String object of the first occurrence of the specified
  • 19. TypescriptBasics M.Manikandan- MMK value, or -1 if not found. lastIndexOf() It returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. localeCompare() It returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. match() It is used to match a regular expression against a string. replace() It is used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. search() It executes the search for a match between a regular expression and a specified string. slice() It extracts a section of a string and returns a new string. split() It splits a String object into an array of strings by separating the string into substrings. substr() It returns the characters in a string beginning at the specified location through the specified number of characters. substring() It 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.
  • 20. TypescriptBasics M.Manikandan- MMK toLocaleUpperCase() The characters within a string are converted to upper case while respecting the current locale. toLowerCase() It returns the calling string value converted to lower case. toString() It returns a string representing the specified object. toUpperCase() It returns the calling string value converted to uppercase. valueOf() It returns the primitive value of the specified object. How to create TypeScript string object:  By using string literals.  By using String() constructor. By using number literals: When we create a number literal browser automatically converts it to Number object. Syntax: var str1:string = “value”; Example: function stringTest(str:string):void{ console.log(str); } var str:string = "Sahdev"; stringTest(str); Try it: By using String() constructor: We can create a TypeScript String object by using String() constructor.
  • 21. TypescriptBasics M.Manikandan- MMK Syntax: var str1:string = new String(value); Example: function stringTest(str:string):void{ console.log(str); } var str:string = new String("Richi"); stringTest(str); TypeScript Boolean Object TypeScript boolean object: A TypeScript Boolean object can represents two values “true” or “false”. How to create TypeScript boolean object:  By using boolean literals.  By using Boolean() constructor. Syntax: Var b1:boolean = true; var b2:boolean = new Boolean(value); Example: function booleanTest(bVar:boolean):void{ console.log(bVar.valueOf()); } var boolean1:boolean=new Boolean(true); var boolean2:boolean=new Boolean(false); var boolean3:boolean=true; booleanTest(boolean1); booleanTest(boolean2); booleanTest(boolean3);
  • 22. TypescriptBasics M.Manikandan- MMK TypeScript Date Object Tutorial TypeScript date object: A TypeScript Date object represents a date. We can get or set year, month and day, hour, minute, second, and millisecond fields of the object by Date methods. TypeScript Date Object Properties: Property Description constructor It specifies the function that creates an object’s prototype. prototype It allows us to add properties and methods to an object TypeScript Date Object Methods: Method Description Date() It returns today’s date and time getDate() It returns the day of the month for the specified date according to local time. getDay() It returns the day of the week for the specified date according to local time. getFullYear() It returns the year of the specified date according to local time. getHours() It returns the hour in the specified date according to local time.
  • 23. TypescriptBasics M.Manikandan- MMK getMilliseconds() It returns the milliseconds in the specified date according to local time. getMinutes() It returns the minutes in the specified date according to local time. getMonth() It returns the month in the specified date according to local time. getSeconds() It returns the seconds in the specified date according to local time. getTime() It returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. getTimezoneOffset() It returns the time-zone offset in minutes for the current locale. getUTCDate() It returns the day (date) of the month in the specified date according to universal time. getUTCDay() It returns the day of the week in the specified date according to universal time. getUTCFullYear() It returns the year in the specified date according to universal time. getUTCHours() It returns the hours in the specified date according to universal time. getUTCMilliseconds() It returns the milliseconds in the specified date according to universal time. getUTCMinutes() It returns the minutes in the specified date according to universal time.
  • 24. TypescriptBasics M.Manikandan- MMK getUTCMonth() It returns the month in the specified date according to universal time. getUTCSeconds() It returns the seconds in the specified date according to universal time. getYear() It returns the year in the specified date according to local time. Use getFullYear instead. setDate() It sets the day of the month for a specified date according to local time. setFullYear() It sets the full year for a specified date according to local time. setHours() It sets the hours for a specified date according to local time. setMilliseconds() It sets the milliseconds for a specified date according to local time. setMinutes() It sets the minutes for a specified date according to local time. setMonth() It sets the month for a specified date according to local time. setSeconds() It sets the seconds for a specified date according to local time. setTime() It sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. setUTCDate() It sets the day of the month for a specified date according to universal time.
  • 25. TypescriptBasics M.Manikandan- MMK setUTCFullYear() It sets the full year for a specified date according to universal time. setUTCHours() It sets the hour for a specified date according to universal time. setUTCMilliseconds() It sets the milliseconds for a specified date according to universal time. setUTCMinutes() It sets the minutes for a specified date according to universal time. setUTCMonth() It sets the month for a specified date according to universal time. setUTCSeconds() It sets the seconds for a specified date according to universal time. setYear() It sets the year for a specified date according to local time. Use setFullYear instead. toDateString() It returns the “date” portion of the Date as a human-readable string. toGMTString() It converts a date to a string, using the Internet GMT conventions. Use toUTCString instead. toLocaleDateString() It returns the “date” portion of the Date as a string, using the current locale’s conventions. toLocaleFormat() It converts a date to a string, using a format string. toLocaleString() It converts a date to a string, using the current locale’s conventions.
  • 26. TypescriptBasics M.Manikandan- MMK toLocaleTimeString() It returns the “time” portion of the Date as a string, using the current locale’s conventions. toSource() It returns a string representing the source for an equivalent Date object; you can use this value to create a new object. toString() It returns a string representing the specified Date object. toTimeString() It returns the “time” portion of the Date as a human-readable string. toUTCString() It converts a date to a string, using the universal time convention. valueOf() It returns the primitive value of a Date object. TypeScript Date Object Methods: Method Description Date.parse() Parses a string representation of a date and time and returns the internal millisecond representation of that date. Date.UTC() It returns the millisecond representation of the specified UTC date and time. How to create TypeScript date object:  new Date()  new Date(milliseconds)  new Date(datestring)
  • 27. TypescriptBasics M.Manikandan- MMK  new Date(year,month,date[,hour,minute,second,millisecond ]) Example: function dateTest(date:Date):void{ var hours=date.getHours(); var minutes=date.getMinutes(); var seconds=date.getSeconds(); console.log("Current Time: "+hours+":"+minutes+":"+seconds); } var date=new Date(); dateTest(date); TypeScript Math Object TypeScript math object: A TypeScript Math object provides no. of properties and methods for performing mathematical operations. Math is not a constructor and all the properties and methods of Math are static. TypeScript Math Object Properties: Property Description E Euler’s constant and the base of natural logarithms, approximately 2.718. LN2 Natural logarithm of 2, approximately 0.693. LN10 Natural logarithm of 10, approximately 2.302. LOG2E Base 2 logarithm of E, approximately 1.442. LOG10E Base 10 logarithm of E, approximately 0.434. PI Ratio of the circumference of a circle to its diameter, approximately 3.14159.
  • 28. TypescriptBasics M.Manikandan- MMK SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707. SQRT2 Square root of 2, approximately 1.414. TypeScript Math Object Methods: Method Description abs() It returns the absolute value of a number. acos() It returns the arccosine (in radians) of a number. asin() It returns the arcsine (in radians) of a number. atan() It returns the arctangent (in radians) of a number. atan2() It returns the arctangent of the quotient of its arguments. ceil() It returns the smallest integer greater than or equal to a number. cos() It returns the cosine of a number. exp() It returns EN, where N is the argument, and E is Euler’s constant, the base of the natural logarithm. floor() It returns the largest integer less than or equal to a number. log() It returns the natural logarithm (base E) of a number. max() It returns the largest of zero or more numbers. min() It returns the smallest of zero or more numbers.
  • 29. TypescriptBasics M.Manikandan- MMK pow() It returns base to the exponent power, that is, base exponent. random() It returns a pseudo-random number between 0 and 1. round() It returns the value of a number rounded to the nearest integer. sin() It returns the sine of a number. sqrt() It returns the square root of a number. tan() It returns the tangent of a number. toSource() It returns the string “Math”. Example: function mathTest(num:number):void{ var squarRoot = Math.sqrt(num); console.log("Random Number: " + num); console.log("Square root: " + squarRoot); } var num:number = Math.random(); mathTest(num); TypeScript Array Object TypeScript array object: A TypeScript Array object represents a collection of elements of the same type. TypeScript Array Object Properties: Property Description
  • 30. TypescriptBasics M.Manikandan- MMK constructor Returns a reference to the array function that created the object. length It reflects the number of elements in an array. prototype It allows us to add properties and methods to an object. TypeScript Array Object Methods: 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. forEach() Calls a function for each element in the array. indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. join() Joins all elements of an array into a string. 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.
  • 31. TypescriptBasics M.Manikandan- MMK 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. slice() Extracts a section of an array and returns a new array. some() Returns true if at least one element in this array satisfies the provided testing function. toSource() Represents the source code of an object sort() Represents the source code of an object splice() Adds and/or removes elements from an array. toString() Returns a string representing the array and its elements. unshift() Adds one or more elements to the front of an array and returns the new length of the array. How to create TypeScript array object:  By using array literals.
  • 32. TypescriptBasics M.Manikandan- MMK  By using Array() constructor. By using array literals: Using an array literal is the simplest way to create a TypeScript Array. Syntax: var array1:string[] = ["element1","element2","elementN"]; Example: function arrayTest(names:string):void{ for (i=0;i<names.length;i++){ console.log(names[i]); } } var names:string[] = ["Bharat","Sahdev","Richi","Harish","Bharti","Deepika","Shaveta"]; arrayTest(names); By using Array() constructor: We can create a TypeScript Array object by using Array() constructor. Syntax: var array1 = new Array(“element1”, “element2”, “elementN”); Example: function arrayTest(names:string):void{ for (i=0;i<names.length;i++){ console.log(names[i]); } } var names:string[] = new Array("Jai","Vivek","Mahesh","Narender","Vishal","Hemant"); arrayTest(names); TypeScript Tuple TypeScript tuples: Typescript tuple represents a heterogeneous collection of values i.e. it contains a collection of values of
  • 33. TypescriptBasics M.Manikandan- MMK different types. Syntax: var tupleName = [value1,value2,value3,…valuen] Example: function tupleTest(values):void{ for (i=0;i<values.length;i++){ console.log(values[i]); } } var values = [10,20,"Gunjan","Rajeev","Vikram","Sudhir"]; tupleTest(values); TypeScript Union Type TypeScript union type: TypeScript Union Type provides the facility to combine one or two types for a variable. The pipe symbol (|) is used to combine the two or more data types. Syntax: var varName: dataType1|dataType2|dataType3 Example: function unionTest(value:string|number):void{ console.log(value); } unionTest("Jai"); unionTest(123); Typescript Interface T Dictionary meaning of interface: A point where two systems, subjects, organizations, etc., meet and interact. TypeScript interface:
  • 34. TypescriptBasics M.Manikandan- MMK An interface is declared with interface keyword. It is a way of implementing 100% abstraction. It only contains the declaration of the members. Interface forms a contract with your class that force your class to have all methods defined by the interface must appear in the class. Syntax: interface interface_name { } Example: interface IPerson { firstName:string, lastName:string, sayHi: ()=>string } var customer:IPerson = { firstName:"Ajay", lastName:"Laddha", sayHi: ():string =>{return "Hi"} } console.log("Customer Object Details: "); console.log(customer.sayHi()); console.log(customer.firstName); console.log(customer.lastName); var employee:IPerson = { firstName:"Vikas", lastName:"Jainer", sayHi: ():string =>{return "Hello"} } console.log("Employee Object Details: "); console.log(employee.sayHi()); console.log(employee.firstName); console.log(employee.lastName);
  • 35. TypescriptBasics M.Manikandan- MMK Typescript Class TypeScript Class: As we discussed in earlier tutorials that TypeScript supports object-oriented programming concepts like classes, interfaces, etc. Class acts as a blue print or template for creating objects. It provides state and behaviour for its objects. A class is used to encapsulate the data for the object. Syntax: class class_name { //field //constructor //function } Typescript creating objects: The new keyword followed by the class name is used to create an instance of the class. var objectName = new className([ arguments ]) Example: class Employee { //field name:string; //constructor constructor(name:string) { this.name = name; } //function display():void { console.log("Employee Name: "+this.name); } } //create an object
  • 36. TypescriptBasics M.Manikandan- MMK var obj = new Employee("Jai"); //access the field console.log("Employee Name: "+obj.name); //access the function obj.display(); TypeScript Abstract Class TypeScript Abstract Class: Abstract class is a way of implementing 0 to 100% abstraction. A class declared with abstract keyword is known as an abstract class. An abstract class may or may not contain abstract method. Abstract classes cannot be instantiated. Syntax: abstract class className { // declare fields // declare abstract/non-abstract methods } Abstract method: A method with no implementation i.e. without braces and followed by a semicolon. Syntax: abstract return_type methodName(); Example: abstract class Department { constructor(public name: string) { } printName(): void { console.log("Department name: " + this.name); }
  • 37. TypescriptBasics M.Manikandan- MMK abstract printMeeting(): void; } class AccountingDepartment extends Department { constructor() { super("Accounting and Auditing"); } printMeeting(): void { console.log("The Accounting Department meets each Monday at 10am."); } generateReports(): void { console.log("Generating accounting reports..."); } } let department: Department; department = new AccountingDepartment(); department.printName(); department.printMeeting(); Typescript Object TypeScript Object: A real world entity is known as an object. Like every real world object, software objects also have state and behavior. State of the object is represented by data members or fields and behavior is represented by methods. In TypeScript an object represents an instance which contains set of key value pairs. The values can be scalar values, functions or array of other objects. Syntax: var objectName = { key1: “value”, //scalar value key2: function() {
  • 38. TypescriptBasics M.Manikandan- MMK //functions }, Key3:[“content1”, “content2”] //collection }; Example: class Employee { //field name:string; empId:string; } //function var display = function(obj: {name:string, empId:string}) { console.log("Employee Name: "+obj.name); console.log("Employee EmpId: "+obj.empId); } //create an object var obj:Employee = {name:"Jai", empId:"EMP024"}; //access the function display(obj); Typescript Duck Typing TypeScript duck typing: Duck-typing is a powerful feature which brings strong typing concepts in TypeScript code. TypeScript provides the duck typing type-checking which focus on the shape that values have. It checks for the presence of certain properties in the objects instead of the actual object type. The following example does not allow substitution of a Parrot for a Duck, because the Duck class has an additional method (so Parrot fails duck typing). Sparrows and Parrots are apparently substitutable in duck typing because there’s nothing a
  • 39. TypescriptBasics M.Manikandan- MMK parrot can do that a sparrow cannot, and vice versa. Of course, a Duck can substitute for a Parrot, because if it sounds like a parrot, it is a parrot. Example: class Sparrow { sound = "cheep"; } class Parrot { sound = "squawk"; } class Duck { sound = "quack"; swim(){ console.log("Going for a dip!"); } } var parrot: Parrot = new Sparrow(); // substitutes var sparrow: Sparrow = new Parrot(); // substitutes var parrotTwo: Parrot = new Duck(); //var duck: Duck = new Parrot(); // IDE & compiler error console.log("Parrot says: "+parrot.sound); console.log("sparrow says: "+sparrow.sound); console.log("parrot says: "+parrotTwo.sound); TypeScript Namespaces TypeScript NameSpace: TypeScript namespace is a way to organize your code. Internal modules in typescript are now referred to namespaces. The namespace keyword is used to define a namespace. Syntax: namespace NameSpaceName { export interface IInterfaceName { } export class ClassName { } }
  • 40. TypescriptBasics M.Manikandan- MMK Access the class or interface in another namespace: NameSpaceName.ClassName; Example: namespace Validation { export interface StringValidator { isValid(s: string): boolean; } const lettersRegexp = /^[A-Za-z]+$/; const numberRegexp = /^[0-9]+$/; export class LettersOnlyValidator implements StringValidator { isValid(s: string) { return lettersRegexp.test(s); } } export class ZipCodeValidator implements StringValidator { isValid(s: string) { return s.length === 5 && numberRegexp.test(s); } } } //Some samples to try let strings = ["You", "53454", "Hello"]; // Validators to use let validators: { [s: string]: Validation.StringValidator; } = {}; validators["ZIP code"] = new Validation.ZipCodeValidator(); validators["Letters only"] = new Validation.LettersOnlyValidator(); //Show whether each string passed each validator for (let s of strings) { for (let name in validators) { console.log(`"${ s }" - ${ validators[name].isValid(s) ? "Valid" : "Invalid" } ${ name }`); } }
  • 41. TypescriptBasics M.Manikandan- MMK TypeScript Multi-file namespaces: We can split the namespace into multiple files. As these multiple files will have dependencies we have to add reference tag to tell the compiler about the relationships between the files. /// <reference path = "FileName.ts" /> Example: Validation.ts namespace Validation { export interface StringValidator { isValid (s: string): boolean; } } LettersValidator.ts /// <reference path="Validation.ts" /> namespace Validation { const lettersRegexp = /^[A-Za-z]+$/; export class LettersOnlyValidator implements StringValidator { isValid (s: string) { return lettersRegexp.test(s); } } } ZipCodeValidator.ts /// <reference path="Validation.ts" /> namespace Validation { const numberRegexp = /^[0-9]+$/; export class ZipCodeValidator implements StringValidator { isValid (s: string) { return s.length === 5 && numberRegexp.test(s); } } } Test.ts
  • 42. TypescriptBasics M.Manikandan- MMK /// <reference path="Validation.ts" /> /// <reference path="LettersValidator.ts" /> /// <reference path="ZipCodeValidator.ts" /> //Some samples to try let strings = ["You", "53454", "Hello"]; // Validators to use let validators: { [s: string]: Validation.StringValidator; } = {}; validators["ZIP code"] = new Validation.ZipCodeValidator(); validators["Letters only"] = new Validation.LettersOnlyValidator(); //Show whether each string passed each validator for (let s of strings) { for (let name in validators) { console.log(`"${ s }" - ${ validators[name].isValid(s) ? "Valid" : "Invalid" } ${ name }`); } } TypeScript Module TypeScript module: A module refers to a set of standardized parts or independent units that can be used to construct a more complex structure. TypeScript modules provides a way to organize the code for better reuse. Syntax: export interface InterfaceName { //Block of statements } The import keyword is used to use the declared module in another file. import testInterfaceRef = require(“./InterfaceName”); Example: IShowDetails.ts
  • 43. TypescriptBasics M.Manikandan- MMK export interface IShowDetails { display(); } Student.ts import showDetails = require("./IShowDetails"); export class Student implements showDetails.IShowDetails { public display() { console.log("Student Details"); } } Teacher.ts import showDetails = require("./IShowDetails"); export class Teacher implements showDetails.IShowDetails { public display() { console.log("Teacher details."); } } TestShape.ts import showDetails = require("./IShowDetails"); import student = require("./Student"); import teacher = require("./Teacher"); function showAllDetails(detailsToShow: showDetails.IShowDetails) { detailsToShow.display(); } showAllDetails(new student.Student()); showAllDetails(new teacher.Teacher()); TypeScript Ambient Module TypeScript ambient module: As we discussed in earlier tutorials TypeScript provides the facility to safely and easily use existing JavaScript libraries like jquery, angularjs, nodejs etc. Ambient declarations allow us to safely use existing popular JavaScript libraries. Ambient declaration files are savedwith .d.ts extension.
  • 44. TypescriptBasics M.Manikandan- MMK Syntax to declare ambient variables or modules: declare module ModuleName { } Syntax to use Ambient files: /// <reference path = "AmbientFileName.d.ts" /> Example: Let us consider that we are using a third party js library with following code. CalcSum.js var TestVar; (function (TestVar) { var Calc = (function () { function Calc() { } Calc.prototype.doSum = function (num1, num2) { return num1 + num2; } } } As this is a js file and we still want to use the doSum() function in our TypeScript code with type safety. We can use this by using ambient declaration. Let us create an ambient declaration file. Calc.d.ts declare module TestVar { export class Calc { doSum(num1:number, num2:number) : number; } } Now we have to include the above ambient declaration into our typescript file. CalcTest.ts /// <reference path = "Calc.d.ts" /> var obj = new TestVar.Calc(); console.log(obj.doSum(10,20));