0% found this document useful (0 votes)
10 views72 pages

MSD Unit4

MEAN STACK TECHNOLOGIES

Uploaded by

dveeraswamy6008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views72 pages

MSD Unit4

MEAN STACK TECHNOLOGIES

Uploaded by

dveeraswamy6008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

lOMoARcPSD|37346256

About TypeScript
Implementing a JavaScript-based application is more error-prone as it supports dynamic typing and supports non-strict mode
with global variables.
TypeScript makes such implementations easy, as it supports static typing and structured code with the help of modules and
object-oriented concepts.
This course introduces various features and programming constructs of TypeScript which enables you to develop a highly
structured, less error-prone JavaScript code using TypeScript features.
Why TypeScript?
JavaScript is the language used for client-side scripting to do client-side validations, DOM manipulation, Ajax calls, etc.
using JavaScript. Also, JavaScript frameworks can be used for writing complex business logic that runs at the client-side.
As the complexity of the JavaScript code increases, it gradually becomes difficult in coding and maintaining. This is because
of the limitations of the JavaScript language. There is no option to change the language for the client-side scripting as the
browser understands only JavaScript.
The solution is to choose a language that is rich in features and the code can be converted to JavaScript. This process of
converting the code written in one language into another language is called Transpilation.( A transpiler is a source-to-
source compiler, converting source code to source code in the same or another language)
TypeScript is one such language where its code can get transpiled to JavaScript.

Pitfalls of JavaScript
 Dynamic Typing: It decides the data type of the variable dynamically at run time.
 Interpreted Language: It is a language in which the code instructions are executed directly without prior
compilation to machine-language instructions.
 Minimal Object-Oriented support: Object-Oriented Programming (OOP) is a programming methodology based
on the concept of objects. Object-Oriented concepts like classes, encapsulation, inheritance help in the readability
and reusability of the code.
 Minimal IDE support: Integrated Development Environment (IDE) is a software application that provides all
necessary options like code refactoring, intelliSense (IntelliSense is a code completion tool that is built into
Microsoft Visual Studio. It is one of a number of similar tools that allow for intelligent code completion or
intelligent text completion on different platforms) support, debugging support to software programmers for
software development.
Dynamic Typing
Consider the below JavaScript function:

1. function calculateTotalPrice(quantity, unitPrice) {


1. return quantity * unitPrice;
2. }

We can invoke this function using the below code:

1. console.log(calculateTotalPrice(3, "500"));

Since JavaScript is dynamically typed, we can invoke the above function using the below code as well.

1. console.log(calculateTotalPrice('three', "500"));

Even though the above code will not throw any error, it will return NaN as output, since the expected number type value is
not passed to the quantity argument of the calculateTotalPrice function.
To avoid the above runtime error we can use static typing in TypeScript, wherein we will add data type to the function
argument while defining it. Consider the same JavaScript function written using TypeScript as below:

1. function calculateTotalPrice(quantity:number, unitPrice:number) {


1. return quantity * unitPrice;
2. }

In the above code, we are adding a number as the data type to both the arguments of the function. Hence when we invoke
the function using the below code:

console.log(calculateTotalPrice('three', "500"));

We will get a compilation error since we are invoking the function with the first parameter as a string type. Hence we can
detect error early at compilation time itself.
Interpreted Language
JavaScript is an interpreted language. The advantages are:
 It takes less amount of time to analyze the source code
lOMoARcPSD|37346256

 Memory efficient as no intermediate object code will get generated.


The disadvantage is most of the errors can be identified only at run time.
This can be overcome by using TypeScript which will be transpiled to JavaScript and most of the errors will be fixed during
the transpilation time itself.
Therefore, TypeScript saves the application development time for a JavaScript developer.
Minimal Object Oriented Support
Consider the below JavaScript code:

1. var __extends = (this && this.__extends) || (function () {


1. var extendStatics = Object.setPrototypeOf ||
2. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
3. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
4. return function (d, b) {
5. extendStatics(d, b);
6. function __() { this.constructor = d; }
7. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8. };
9. })();
10. var Product = (function () {
11. function Product() {
12. }
13. return Product;
14. }());
15. var Gadget = (function (_super) {
16. __extends(Gadget, _super);
17. function Gadget() {
18. return _super !== null && _super.apply(this, arguments) || this;
19. }
20. Gadget.prototype.getProduct = function () {
21. };
22. return Gadget;
23. }(Product));

The equivalent Typescript code is as below:

1. class Product{

1. protected productId:number;
2. }
3. class Gadget extends Product{
4. getProduct():void{
5. }
6. }

You can observe from the above code that:


 The readability of the JavaScript code is minimal.
 Abstraction is done using closures or self-invoking functions wherein the number of lines of code is more
compared to public, private, protected access modifiers.
 Classes are created using a constructor function, which leads to confusion compared to using the class keyword.
 Javascript supports OOP through prototypal inheritance which is complex for people with classical inheritance
background to understand.
All the above-mentioned features are supported by TypeScript. In addition to that TypeScript also supports interface and
generic concepts which is not supported by JavaScript.
Minimal IDE Support
A few IDEs have code refactoring, IntelliSense support for JavaScript application development.
 IntelliSense support helps in writing the code quickly.
 Refactoring support helps in changing the variable or function names throughout the application quickly.
Most of the IDEs has good support for TypeScript, some are listed below:
 Visual Studio with versions 2015, 2013, and so on
 Sublime Text
 Atom
 Eclipse
 Emacs
 WebStorm
 Vim
Why TypeScript?
lOMoARcPSD|37346256

JavaScript application development has become easier with the help of the following tools:
 npm can be used to download packages
 webpack can be used to manage the complexity of applications.
 Babel can be used to fetch the latest features of the language.
 Tools like rollup and uglifyjs can be used to optimize application payloads.
 prettier and eslint can be used to uphold code with consistent style as well as quality.
 IDE like Visual Studio Code with Node.js environment can be used to run JavaScript code everywhere.
There is browser support challenge for the latest ES6 version of JavaScript. You can use ES6 transpilers like Babel to
address this.
TypeScript can be another preferred option which is a superset of JavaScript and transpiles to the preferred version of
JavaScript.
What is TypeScript?
TypeScript can be considered as a typed superset of JavaScript, that transpiles to JavaScript.
 Transplier converts the source code of one programming language to the source code of another programming
language.
 TypeScript makes the development of JavaScript more of a traditional object-oriented experience.
 TypeScript is based on ECMAScript 6 and 7 proposals.
 Any valid JavaScript is TypeScript.
Relationship between TypeScript and JavaScript
TypeScript implements EcmaScript specification. Apart from the EcmaScript specification, TypeScript has its own features
as well.
JavaScript also implements EcmaScript.
TypeScript code must be transpiled to JavaScript code to use it in an application.

From the above code, the TypeScript class Helloworld is converted to a self-invoking function in JavaScript when transpiled.
You can use TypeScript's online playground editor to see how TypeScript gets converted into JavaScript.
Features of TypeScript
Static Typing: It adds static typing to JavaScript, due to which the readability of the code improves and helps in finding
more early compilation errors than run time errors.
Modules support: TypeScript provides an option to create modules to modularize the code for easy maintenance. Modules
help in making the application scalable.
Object-Oriented Programming: TypeScript supports Object-Oriented Programming features such as class, encapsulation,
interface, inheritance and so on which helps in creating highly structured and reusable code.
Open Source: TypeScript is open source. The source code of TypeScript can be downloaded from Github.
Cross-Platform: It works across the platform.
Tooling Support: TypeScript works extremely well with Sublime Text, Eclipse, and almost all major IDEs compared to
JavaScript.
Installing TypeScript – Internal

To install TypeScript, go to the official site of TypeScript ( http://www.typescriptlang.org/ ) and follow the steps mentioned
there to download TypeScript.
lOMoARcPSD|37346256

As mentioned on the official site, you need to install Node.js.

Install Node.js from the official site of Node.js ( https://nodejs.org/en/) or Software Center.

Open a Node.js command prompt and check whether node and npm are installed in your machine by using "node -v " and
"npm -v" commands.

npm is a command-line tool that comes along with Node.js installation with which you can download node modules.
TypeScript is also such a node module that can be installed using npm.

Open Node.js command prompt, execute the below commands as shown below to download the TypeScript node module
from the local Infosys repository.

Setup the registry:


npm config set registry https://infyartifactory.ad.infosys.com/artifactory/api/npm/npm/
In the same Node.js command prompt, type the "npm i –g typescript" command to download the TypeScript module from
the repository.

On successful execution of above command, the TypeScript module will get downloaded under folder
C:\Users\<<username>>\AppData\Roaming\npm\node_modules\typescript as shown below.

In the same command prompt check for TypeScript installation as below:

1. tsc -v
1. //or
2. tsc --version

Output showing version number indicates the successful installation of the TypeScript module.
Alternatively, you can also use TypeScript online playground editor in this case, you should be always connected to good
Internet.
To configure TypeScript with different IDEs. Here are a few links for IDE configuration for TypeScript:
 Visual Studio Code: https://code.visualstudio.com/Docs/languages/typescript
 Eclipse IDE: https://github.com/palantir/eclipse-typescript
 Visual Studio 2015: https://angular.io/guide/visual-studio-2015

Installing TypeScript

To install TypeScript, go to the official site of TypeScript and follow the steps mentioned there to download TypeScript.
As mentioned on the official site, you need to install Node.js.
Install Node.js from the official site of Node.js.
Open a Node.js command prompt and check whether node and npm are installed in your machine by using "node
-v" and "npm -v" commands.
npm is a command-line tool that comes along with Node.js installation with which you can download node modules.
TypeScript is also such a node module that can be installed using npm.
Open a Node.js command prompt and use the command "npm i –g typescript" to download the TypeScript module from
the npm repository.
lOMoARcPSD|37346256

Latest typescript module will get downloaded under folder


C:\Users\<<username>>\AppData\Roaming\npm\node_modules\typescript as shown below.

In the same command prompt check for TypeScript installation as below:

1. tsc -v
1. //or
2. tsc --version

Output showing version number indicates the successful installation of the TypeScript module.
Alternatively, you can also use TypeScript online playground editor in this case you should be always connected to the
Internet.
To configure TypeScript with different IDEs. Here are some of the popular IDEs for working with TypeScript:
 Visual Studio code
 Eclipse IDE
 Visual Studio 2015
First TypeScript Application
To start with the first application in TypeScript, create a file hello_typescript.ts under a folder. In the ts file give a console.log
statement and save it.

From the Node.js command prompt, navigate to the directory in which the ts file resides and compile the ts file using the tsc
command.

After compilation of the TypeScript file, the corresponding JavaScript file gets generated.

To run the generated JavaScript file, use the node command from the command line or include it in an HTML page using the
script tag and render it in the browser.
Demo steps:
Step 1: Create a file hello_typescript.ts
hello_typescript.ts

1. console.log('Hello welcome to TypeScript');

Step 2: From the command prompt navigate to the folder in which the ts file resides and compile the ts file using the tsc
command.
lOMoARcPSD|37346256

Step 3: Run the compiled js file using node command as below:

Basics of TypeScript

Consider the below page of the Mobile Cart application. The information such as mobile phone name, price, status on the
availability of the mobile, discounts is displayed on the page. It also displays different price ranges as GoldPlatinum,
PinkGold, SilverTitanium.

Each of the information getting displayed has a specific type. For example, the price can only be numeric and the mobile
name can only be a string.
There should be a mechanism using which you can restrict the values being rendered on the page.
Sometimes it is preferred to have a text instead of numeric values to represent some information. For example, on the above
page instead of categorizing the mobiles based on their prices, you can prefer to remember them as some text
like GoldPlatinum, PinkGold, etc.
TypeScript is a static typed language that allows us to declare variables of various data types so that you ensure only the
desired type of data being used in the application.
Let us discuss declaring variables and basic data types supported by TypeScript.
Declaring Variables
Declaration of a variable is used to assign a data type and an identifier to a variable. Declaration of variables in TypeScript is
like JavaScript variable declaration.
Below are the three declaration types supported in TypeScript.

Data Type Explanation

 Variable declared with this type would have function scope.


 They can be re-assigned and re-defined.
var
 When a variable declared outside the function, it would have global scope
and automatically attaches itself to the window object.
lOMoARcPSD|37346256

 Variable declared with this type would have a block-level scope.


let
 They can be re-assigned and cannot be redefined.

 Variable declared with this type would have a block-level scope.


const
 They can be neither re-assigned nor re-defined.
Problem with var declaration:
In the below code, you will observe a strange behavior of the variable count. You can access this variable even outside the
loop although it is defined inside the loop. This is due to the global scope nature of the var data type declaration.

Output:

Some of the other problems with global scope variable are:

 When the var declared variable is defined outside a function it is attached with the window object which has only
one instance.
 This is a bad practice and causes an overridden of a variable when you try to use a third-party library working with
the same variable.
 Generally, var variables have a function-scope and if they are not declared within a function, they have a global
scope.
To overcome this issue, in ES2015. JavaScript has introduced let and const as two new declaration types and it is considered
as standard because declaring variables by these two data types are safer than declaring a variable using the var keyword.
Let us learn about these declarations.
Declaring variables using let keyword
Declaring Variables using let:
When a developer wants to declare variables to live only within the block, they can achieve a block-scoped
variable using let declaration.
Let us replace the var with the let keyword in the previous for loop code-snippet and observe the difference.

Output:

Since the count variable is a block-scoped, it is not accessible outside the for loop hence results in the error as not defined.
Difference between var and let Keyword
Capturing Variable in the loop
Variable declared using var keyword will have function scope. So, even if you declare a variable using var inside a loop, it
will have function scope.
In the below example, variable i has been declared inside the for loop using the var keyword, but it will have the scope of
the function. Thus, by the time setTimeout function executes, the value of i has already reached 10.
lOMoARcPSD|37346256

Therefore, every invocation of setTimeout function gets the same value of i as 10.

Variable declared using let keyword will have block scope. Therefore, once the block is terminated, the scope also is lost.

In the below example, variable i has been declared using let inside the for loop. So, its scope will be limited to one iteration
of the loop.

In this scenario, every invocation of the setTimeout function will get the value of i from that iteration scope.

Redeclaring block-scoped variable:

The let declared variable cannot be redeclared within the same block.

The var declared variable can be redeclared within the same block.

Due to these reasons let declaration is preferred over var declaration.


Now let us see what is const declaration meant for.
Declaring variables using const Keyword
The const declaration is similar to the let declaration except that the value cannot be re-assigned to the variable.

const declared variables are mutable if declared as an array or as an object literal.

this declaration should be used if the value of the variable should not be reinitialized.

Basic Types
Data type mentions the type of value assigned to a variable. It is used for variable declarations.
Since TypeScript supports static typing, the data type of the variable can be determined at the compilation time itself.
lOMoARcPSD|37346256

There are variables of different types in TypeScript code based on the data type used while declaring the variable.
boolean:
boolean is a data type that accepts only true or false as a value for the variable it is been declared.
In a shopping cart application, you can use a boolean type variable to check for the product availability, to show/hide the
product image, etc.

number:
number type represents numeric values. All TypeScript numbers are floating-point values.
In a shopping cart application, you can use number type to declare the Id of a product, price of a product, etc.

string:

A string is used to assign textual values or template strings. String values are written in quotes – single or double.

In a shopping cart application, you can use string type to declare variables like productName, productType, etc.

Template strings are types of string value that can have multiple lines and embedded expressions. They are surrounded by
the backquote\backtick (`) character and embedded expressions of the form ${ expr }.

any:
any type is used to declare a variable whose type can be determined dynamically at runtime with the value supplied to it. If
no type annotation is mentioned while declaring the variable, any type will be assigned by default.
In a shopping cart application, you can use any type to declare a variable like screenSize of a Tablet.

void:

void type represents undefined as the value. the undefined value represents "no value".
A variable can be declared with void type as below:

void type is commonly used to declare function return type. The function which does not return a value can be declared with
a void return type. If you don’t mention any return type for the function, the void return type will be assigned by default.

Type Annotations
Type Annotation is a way to enforce type restriction to a specific variable or a function.
If a variable is declared with a specific data type and another type of value is assigned to the variable, a compilation error
will be thrown.
lOMoARcPSD|37346256

Tryout : Basic Types


Problem Statement
Code in TypeScript

1.// Declaring variables with basic types using let

2.let productId: number = 1045; // Declaring a numeric variable

3.let productDescription: string = '16GB, Gold'; // Declaring a string variable

4.let productName: string = 'Samsung Galaxy J7';

5.let productAvailable: boolean = true; // Declaring a boolean variable

6. console.log('The type of productId is ' + typeof productId);

7.console.log('The type of productAvailable is ' + typeof productAvailable);

8.console.log('The type of productName is ' + typeof productName);

9.// Declaring variables using const

10.const discountPercentage: number = 15;

11. console.log('Discount percentage is:' + discountPercentage);


Exercise : Basic Types
Problem Statement:
Create the below page of the Mobile Cart application:
Design the below screen:

To solve this problem, you will need HTML code to show the image, text, and labels.
For the value of Mobile name, price, and status information, write TypeScript code.
In the TypeScript code, use the below statement to update the designated place in the HTML page.
document.getElementById("pName").innerHTML=mobileName;
Here, mobileName is a TypeScript variable and pName is the id of the HTML element where the mobile name has to be
displayed.
Similarly, price and status information need to be rendered on the HTML page.
Below is the complete HTML code for the page, write the TypeScript code for updating the information of mobile name,
price, status, and discount.
<!doctype html>
<html>
<head>
lOMoARcPSD|37346256

<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<style>
.navbar-inverse {
background-color:#005580;
background-image: none;
background-repeat: no-repeat;
color:#ffffff;
}
.navbar-inverse .navbar-nav > .active > a {
color: #ffffff;
background-color:transparent;

}
.navbar-inverse .navbar-nav > li > a:hover{
text-decoration: none;
color: #ffffff;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-
expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>

</ul>
<!--/.nav-collapse -->
<ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
<li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart" style="color:white"></span></a></li>
</ul>
</div>
</nav>
<div style="margin-top:7%">
<center> <h2>Your Favorite Online Mobile Shop!</h2> </center>
</div>
<div class="container" style="padding-top:5%">
<div class="row">
<div class="col-md-4">
<div style="text-align: center;">
<img src="Images/Part 1/SamsungGalaxy_Gold.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div style="cursor:pointer;color:Steelblue;text-align: center;"><b>
<span id="pName"></span></b></div>
<div style="padding-top:10px;padding-left: 101px;"><b>Price:</b>&nbsp;&dollar;<span
id="pPrice"></span></div>
<div style="padding-left: 100px;"><b>Status:</b><span id="pAvailable"></span></div>
lOMoARcPSD|37346256

</div>
</div>
</div>
</div>
</body>
<!--Adding the converted js file -->
<script src="productlist.js"></script>
</html>
Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.
Download the images to be used in the exercise application.
Enum

Enum in TypeScript is used to give more friendly names to a set of numeric values.

For example, if you need to store a set of size variables such as Small, Medium, Large with different numeric values, group
those variables under a common enum called Size.

By default, enum’s first item will be assigned with zero as the value and the subsequent values will be incremented by one.

In a shopping cart application, you can use a MobilePrice enum to store different prices of the mobile depending on the
mobile color.

To get the value from an enum use one of the following:

Enum items can also be initialized with different values than the default value. If you set a different value for one of the
variables, the subsequent values will be incremented by 1.

You can even set different values to different enum items

Tryout : Enum
Problem Statement
// declaring enum variable and assigning default values
enum MobilePrice {Black= 250, Gold= 280, White= 300}

// functon to calculate final amount


function calculateAmount(price: number): number {
let discount: number;
let totalAmount: number;
if (price === MobilePrice.Gold) {
discount = 5;
} else if (price === MobilePrice.White) {
discount = 8;
} else {
discount = 10;
}
totalAmount = price - price * discount / 100;
return totalAmount;
}
lOMoARcPSD|37346256

// lines to populate the Actual and Final price of Black color Mobile
console.log('Actual price of the Mobile is $' + MobilePrice.Black);
console.log('The final price after discount is $' + calculateAmount(MobilePrice.Black));
Exercise : Enum
Problem Statement:

Create the below page of the Mobile Cart application:


Design the below screen:

In the previous Mobile Cart exercise page, you have rendered the Mobile phone name, price, status on the availability of the
mobile, and discount details.
On the page, display the price of the mobile-based in three different colors. Instead of using the number in our code,
represent them by string values like GoldPlatinum, PinkGold, SilverTitanium.
Below is the complete HTML code for the page, write the TypeScript code to declare enum variable to represent the price of
mobiles and update the page using these enum values.
<!doctype html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

<style>
.navbar-inverse {
background-color:#005580;
background-image: none;
background-repeat: no-repeat;
color:#ffffff;
}
.navbar-inverse .navbar-nav > .active > a {
color: #ffffff;
background-color:transparent;

}
.navbar-inverse .navbar-nav > li > a:hover{
text-decoration: none;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-
expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
lOMoARcPSD|37346256

<ul class="nav navbar-nav">


<li ><a href="Index.html">Home</a></li>
</ul>
<!--/.nav-collapse -->
<ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
<li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart" style="color:white"></span></a></li>
</ul>
</div>
</nav>

<div class="container" style="margin-top:7%">


<div class="row">
<div class="col-sm-4">
<div style="margin-left:40%;padding-top:15px;">
<div style="padding:15px;">
<div>
<img id="phoneImage" src ="Images/Part 1/samsung_edge_silver.jpg" height="250px" >
</div>
<div style="padding-top:10px;">
<div><b><span id="pName"></span></b></div>
<div style="padding-top:10px;"><b>Price:</b>&nbsp;&dollar;<span id="pPrice"></span></div>
<div><b>Status:</b>&nbsp;<span id="pAvailable"></span></div>
<div><b class="text-danger">Discount:</b>&nbsp;<span id="pDiscount"></span></div>
</div>
</div>
</div>
</div>
<div></div>
<div style="padding-top:15px;">
<div>
<img src ="Images/Part 1/goldmobile.png" style="padding-left:15px;cursor:pointer;" onclick="getMobileByColor('gold');"
>
<img src ="Images/Part 1/pinkmobile.png" style="cursor:pointer;padding-left:15px;" onclick="getMobileByColor('pink');"
>
<img src ="Images/Part 1/silvermobile.png" style="cursor:pointer;padding-left:15px;"
onclick="getMobileByColor('silver');" >

</div>
<div style="padding-top:10px;">
<span style="padding-left:20px;">
GoldPlatinum
</span>
<span style="padding-left:38px;">
PinkGold
</span>
<span style="padding-left:40px;">
SilverTitanium
</span>
</div>
<div style="padding-top:10px;">
<span style="padding-left: 20px;">&dollar;</span><span id="gold" style="padding-left: 2px;"></span>
<span style="padding-left: 90px;">&dollar;</span><span id="pinkgold" style="padding-left: 2px;"></span>
<span style="padding-left: 65px;">&dollar;</span><span id="silver" style="padding-left: 2px;"></span>
<div id="productDescription" style="padding-top:5%;width:70%;text-align:justify">
Samsung Galaxy Note 7 is a stylish mobile you can ever have. It has 64GB memory.
</div>
<div style="padding-top:5%;padding-right:10%">
<button class="btn btn-success" onclick="addtoCart();">Add to Cart</button>
<a style="padding-left:10px;" onclick="backHome();">Back</a>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
lOMoARcPSD|37346256

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Adding converted js code-->
<script src="productdetail.js"></script>
</html>
Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.
Arrays
Consider the below page of the Mobile Cart application that displays the list of mobile phones available. For each mobile in
the list, you can see its image, name, price, and availability status.

This requirement is implemented using the concept of arrays of TypeScript. Let us discuss arrays in TypeScript.
An Array is used to store multiple values in a single variable. You can easily access the values stored in an array using the
index position of the data stored in the array.
TypeScript array is an object to store multiple values in a variable with a type annotation. They are like JavaScript arrays.
Arrays can be created using one of the below:

A TypeScript array defined with a specific type does not accept data of different types. TypeScript arrays can be accessed and
used much like JavaScript arrays.
JavaScript Arrays has several useful properties and methods to access or modify the given array. The same is supported in
TypeScript.
To add a dynamic value to an array, you can either use the push function or use the index reference.

Data can be removed from an array using the pop function or splice function
lOMoARcPSD|37346256

The splice function removes the item from a specific index position.
Tryout : Arrays
Problem Statement
Code in TypeScript
// declaring an array of any datatype
const manufacturers: any[] = [{ id: 'Samsung', checked: false },
{ id: 'Motorola', checked: false },
{ id: 'Apple', checked: false },
{ id: 'Sony', checked: false }
];

console.log('Available Products are: ');

// logic to populate the above declared array's id value


for (const item of manufacturers) {

console.log(item.id);
}
Exercise : Arrays
Problem Statement:
Consider the below requirement of the Mobile Cart application:
Design the below screen:

The above page has objects which represent data about the mobile which will be used to render the details of the mobiles on
the page.
Example of a Product object:

1. {pId:432,productName:"Samsung Galaxy Note


7",productPrice:59000,productAvailable:true,imageUrl:"SamsungGalaxy_Gold.jpg",
1. productDescription:"Samsung Galaxy Note 7 is a stylish mobile you can ever have. It has 64GB memory."
2. }

Create such product objects and place them into a productlist array. Render the above screen with product details from this
array.
Write the TypeScript code to solve the above requirement. The complete HTML code is given below:
<!doctype html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
lOMoARcPSD|37346256

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>

<style>
.navbar-inverse {
background-color:#005580;
background-image: none;
background-repeat: no-repeat;
color:#ffffff;
}
.navbar-inverse .navbar-nav > .active > a {
color: #ffffff;
background-color:transparent;

}
.navbar-inverse .navbar-nav > li > a:hover{
text-decoration: none;
color: #ffffff;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-
expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
</ul>
<!--/.nav-collapse -->
<ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
<li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart" style="color:white"></span></a></li>

</ul>
</div>
</nav>
<div style="margin-top:7%">
<center> <h2>Your Favorite Online Mobile Shop!</h2> </center>
</div>
<div class="container" style="padding-top:5%">
<div class="row">
<div class="col-md-4">
<div style="text-align: center;">
<img src="Images/Part 1/SamsungGalaxy_Gold.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails();" style="cursor:pointer;color:Steelblue;text-align: center;"><b><span
id="pName0"></span></b></div>
<div style="padding-top:10px;padding-left: 101px;"><b>Price:</b>&nbsp;&dollar;<span
id="pPrice0"></span></div>
<div style="padding-left: 100px;"><b>Status:</b><span id="pAvailable0"></span></div>
</div>
</div>
<div class="col-md-4">
<div style="text-align: center;">
<img src="Images/Part 1/samsung_edge_silver.jpg" height="250px">
</div>
<div style="padding-top:10px;">
lOMoARcPSD|37346256

<div onclick="getMobileDetails('samsungedge',231);" style="cursor:pointer;color:Steelblue;text-align:


center;"><b><span id="pName1"></span></b></div>
<div style="padding-top:10px;padding-left: 95px;"><b>Price:</b>&nbsp;&dollar;<span
id="pPrice1"></span></div>
<div style="padding-left: 94px;"><b>Status:</b><span id="pAvailable1"></span></div>
</div>
</div>
<div class="col-md-4">
<div style="text-align: center;">
<img src="Images/Part 1/lumia_640xl.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails('lumia',875);" style="cursor:pointer;color:Steelblue;text-align: center;
"><b><span id="pName2"></span></b></div>
<div style="padding-top:10px;padding-left: 118px;"><b>Price:</b>&nbsp;&dollar;<span
id="pPrice2"></span></div>
<div style="padding-left: 117px;"><b>Status:</b><span id="pAvailable2"></span></div>
</div>
</div>
</div>

</div>

</body>
<!--Adding the converted js file -->
<script src="arrays.js"></script>
</html>
Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.
Tuple
Tuple type is a kind of array which accepts more than one predefined type of data. Arrays are used to represent a collection
of similar objects, whereas tuples are used to represent a collection of different objects.

Let us consider an example, where customerCreditId, Customer object, and customerCreditLimit must be represented in a
data type.

The choice could be to define a class, with these properties. If it is represented using the class, then there will be a
requirement to instantiate the class and then the properties can be accessed.

Tuples provides an easy way to implement the same scenario with an array-like data structure, which is easy to access and
manipulate.

In order to access the customerCreditId, you can use customerCreditInfo[0].

In order to access the customer object, you can use customerCreditInfo[1].


In a shopping cart application, you can use tuples to store product details that should require more than one type of data.
 The order of the first set of data entries while initializing a tuple variable should be the same as the order in which
the type is declared in a tuple.
 A developer can initialize only one entry as per TypeScript data restriction length policy.
 A compilation error will be thrown in below two cases:
o if you are trying to assign multiple entries in the first initialization.
o if you try to initialize different datatypes directly to the tuple declared variable.
 In order to overcome the above-mentioned compilation errors, you can use the push() method.
Example:

In the above example, the underlined error is due to multiple declarations in the first initialization which violates the length
restriction policy. To avoid this, the push method can be used as shown in the code.
lOMoARcPSD|37346256

Tryout : Tuple
Problem Statement
Consider that a developer needs to declare a Tuple variable named productAvailable consisting of two parameters like string
and boolean and needs to populate the message "The product <<productName value>> is available" when availability
parameter is true and populate the message "The product <<productName value>> is not available" when availability
parameter is false and need have appropriate logic to assign productName respectively. Below mentioned code-snippet
would fit into this requirement.

Activity:

Modify line no 11 as given below and re-execute the code.


productAvailable.push("Samsung Galaxy J5",false,1);

Modify line no 11 as given below and re-execute the code.


productAvailable.push(false,"Samsung Galaxy J5");
// declaring a Tuple
let productAvailable: [string, boolean];

let productName;
let availability;

// assigning value to Tuple


productAvailable = ['Samsung Galaxy J7', true];

// Adding new value to Tuple


productAvailable.push('Samsung Galaxy J5', false);

// logic to check product availability based on datatype of declared Tuple variable


for (const item of productAvailable) {
if (typeof item === 'string') {
productName = item;
} else if (typeof item === 'boolean') {
availability = item;
if (availability === true) {
console.log(`The product ${productName} is available`);
} else if (availability === false) {
console.log(`The product ${productName} is not available`);
}
}
}
Why Function?

Consider the below page that displays the list of mobile phones available. For each mobile in the list, you can see its image,
name, price, and availability status. The property ‘name’ of the mobile is clickable.
lOMoARcPSD|37346256

When the mobile name link is clicked, the user is navigated to the next screen which shows the details specific to the phone
selected. The details such as different colors in which the phone is available, price of mobile according to the color selected,
description of the phone, availability status, and discounts if any.

Users can click on each color to view the mobile image for that color. The Price corresponding to the color selected can also
be shown. For example: On click of PinkGold the below screen should be rendered:

This requirement is implemented using the function concept in TypeScript that helps us to implement business logic and
event handlers. Let us discuss functions in TypeScript.

Function in TypeScript Vs JavaScript:

 A function is a block of statements to perform a particular task.


 A sequence of statements written within function forms function body.
 Functions are executed when it is invoked by a function call. Values can be passed to a function as function
parameters and the function returns a value.
 Functions in TypeScript are like functions in JavaScript with some additional features.

TypeScript JavaScript

Types: Supports Do not support

Required and optional parameters: Supports All parameters are optional

Function overloading: Supports Do not support

Arrow functions: Supports Supported with ES2015

Default parameters: Supports Supported with ES2015

Rest parameters: Supports Supported with ES2015


Parameter Types and Return Types
The parameter type is the data type of the parameter and the return type is the data type of the returned value from the
function.
With the TypeScript function, you can add types to the parameter passed to the function and the function return types.
While defining the function, return the data with the same type as the function return type. While invoking the function you
need to pass the data with the same data type as the function parameter type, or else it will throw a compilation error.
lOMoARcPSD|37346256

Tryout : Parameter Types and Return Types


Problem Statement
Consider that developer needs to declare a function - getMobileByManufacturer which accepts string as input parameter and
returns the list of mobiles then below mentioned code-snippet fits into requirement.
Activity:
Comment the line nos 9, 13 and 17 and re-execute the code.
Modify line no 22 as below and re-execute the code.
console.log("The available mobile list:"+getMobileByManufacturer("Nokia"));

// declaring a function which accepts string datatype as parameter and returns string array
function getMobileByManufacturer(manufacturer: string): string[] {

let mobileList: string[];

if (manufacturer === 'Samsung') {


mobileList = ['Samsung Galaxy S6 Edge', 'Samsung Galaxy Note 7',
'Samsung Galaxy J7 SM-J700F'];
return mobileList;
} else if (manufacturer === 'Apple') {
mobileList = ['Apple iPhone 5s', 'Apple iPhone 6s ', 'Apple iPhone 7'];
return mobileList;
} else {
mobileList = ['Nokia 105', 'Nokia 230 Dual Sim'];
return mobileList;
}
}

// logic to populate the Samsung manufacturer details on console


console.log('The available mobile list: ' + getMobileByManufacturer('Samsung'));
Arrow Function
Arrow function is a concise way of writing a function. Whenever you need a function to be written within a loop, the arrow
function will be the opt choice.

Do not use the function keyword to define an arrow function.

In a shopping cart application, you can use the arrow function to perform filtering, sorting, searching operations, and so on

Handling ‘this’ keyword in JavaScript

In a class, if a method wants to access the property of the class it should use this keyword.
For a particular object, this keyword will help to access the properties of the current object. This is possible because all the
methods and properties are within the same scope.
In the above example, when you use this.productName inside the getProductDetails method, getProductDetails method, and
productName variable are in the same scope. Also, you get the desired result.
But when you use this.productName inside the setTimeout function, instead of directly using it in testThisFunction method,
the scope of this.productName will be inside the setTimeout's callback function and not the testThisFunction method. That is
the reason you are unable to access the value of productName for that particular object.
lOMoARcPSD|37346256

If you need to access the class scope with this keyword inside the callback function then use the arrow function.
Arrow function lexically captures the meaning of this keyword.
Rewrite the same logic using the arrow function as below:

In the above code, this.productName is written inside an arrow function. Since the callback function of setTimeout is
implemented using the arrow function, it does not create a new scope and it will be in the same scope as the testThisFunction
**method.
Tryout : Arrow Function
Problem Statement
Consider that developer needs to declare a manufacturer's array holding 4 objects with id and price as a parameter and needs
to implement an arrow function - myfunction to populate the id parameter of manufacturers array whose price is greater than
or equal to 200 dollars then below mentioned code-snippet would fit into this requirement.
Activity:
 Modify the arrow function logic to populate the price value when the id is Apple and re-execute the code.
 Modify the for loop logic to populate only Microsoft manufacture id and price details and re-execute the code.
Code in TypeScript
// declaring an Array with 3 objects
const manufacturers = [{ id: 'Samsung', price: 150 },
{ id: 'Microsoft', price: 200 },
{ id: 'Apple', price: 400 },
{ id: 'Micromax', price: 100 }
];
let test;
// Arrow function to populate the details of Array whose price is greater than 200
function myFunction() {
test = manufacturers.filter((manufacturer) => manufacturer.price >= 200);
}
// self-invoking an arrow function
myFunction();
console.log('Details of Manufacturer array are : ');
// logic to populate the manufacturer array details based on id value
for (const item of test) {
console.log(item.id);
}
Function Types

Function types are a combination of parameter types and return type. Functions can be assigned to variables.

While assigning a function to a variable make sure that the variable declaration is the same as the assigned function’s
return type.

Optional and Default Parameters


TypeScript treats every function parameter as mandatory. So when a function is compiled, the compiler will check whether
there is a value supplied to all the parameters of the function, or else it will throw a compilation error.
Consider the code below:
lOMoARcPSD|37346256

In the above example, you have tried to invoke a function with only a single parameter, whereas the definition of the
function accepts two parameters. Hence, it will throw a compilation error. Also, optional parameter can be used to tackle this
issue.
The Optional parameter is used to make a parameter, optional in a function while invoking the function.
If you rewrite the previous code using an optional parameter, it looks like the below:

An Optional parameter must appear after all the mandatory parameters of a function.
Default parameter is used to assign the default value to a function parameter.
If the user does not provide a value for a function parameter or provide the value as undefined for it while invoking the
function, the default value assigned will be considered.
If the default parameter comes before a required parameter, you need to explicitly pass undefined as the value to get the
default value.

Tryout : Optional and Default Parameters


Problem Statement
Consider that developer needs to declare a function - getMobileByManufacturer with two parameters namely manufacturer
and id, where manufacturer value should passed as Samsung and id parameter should be optional while invoking the
function, if id is passed as 101 then this function should return Moto mobile list and if manufacturer parameter is either
Samsung/Apple then this function should return respective mobile list and similar to make Samsung as default Manufacturer.
Below mentioned code-snippet would fit into this requirement.

Activity:

Modify the function declaration line no 2 as below and re-execute the code.
function getMobileByManufacturer(manufacturer,id?:number): string[]

Modify the line no 35 as below and re-execute the code.


console.log("The available mobile list : " + getMobileByManufacturer(undefined));

console.log("The available mobile list : " + getMobileByManufacturer(101));

console.log("The available mobile list : " + getMobileByManufacturer(undefined,102));


Code in TypeScript
// declaring a function with optional parameter
function getMobileByManufacturer(manufacturer: string = 'Samsung', id?: number): string[] {

let mobileList: string[];

// logic to be evaluated if id parameter while invoking above declared function


lOMoARcPSD|37346256

if (id) {
if (id === 101) {
mobileList = ['Moto G Play, 4th Gen', 'Moto Z Play with Style Mod'];
return mobileList;
}
}

// logic to return mobileList based on manufacturer category


if (manufacturer === 'Samsung') {
mobileList = [' Samsung Galaxy S6 Edge', ' Samsung Galaxy Note 7',
' Samsung Galaxy J7 SM-J700F'];
return mobileList;
} else if (manufacturer === 'Apple') {
mobileList = [' Apple iPhone 5s', ' Apple iPhone 6s', ' Apple iPhone 7'];
return mobileList;
} else {
mobileList = [' Nokia 105', ' Nokia 230 Dual Sim'];
return mobileList;
}
}

// statement to invoke function with optional parameter


console.log('The available mobile list : ' + getMobileByManufacturer('Apple'));

// statement to invoke function with default parameter


console.log('The available mobile list : ' + getMobileByManufacturer(undefined, 101));
Rest Parameter
Rest Parameter is used to pass multiple values to a single parameter of a function. It accepts zero or more values for a single
parameter.

Rest Parameter should be declared as an array.

Precede the parameter to be made as rest parameter with triple dots.

Rest parameter should be the last parameter in the function parameter list.

Tryout : Rest Parameter


Problem Statement
Consider that developer needs to implement business logic for adding multiple Product values into a cart variable which is
type of string array. Below mentioned code-snippet fits into the requirement.
Activity:

 Modify line no 2 as given below and re-execute the code.


let cart: string=[];

 Modify line no 8 as given below and re-execute the code.


function addtoCart(productName: string[]): string[]

 Modify line no 18 as given below and re-execute the code.


console.log("Cart Items are:"+addtoCart("Moto G Play, 4th Gen","Apple iPhone 5s",1));
Code in TypeScript
// declaring a empty string array
const cart: string[] = [];

// arrow function logic to push values into cart array


lOMoARcPSD|37346256

const pushtoCart = (item: string) => { cart.push(item); };

// logic to add items into cart


function addtoCart(...productName: string[]): string[] {

for (const item of productName) {


pushtoCart(item);
}
return cart;

// to populate value on console


console.log('Cart Items are:' + addtoCart(' Moto G Play, 4th Gen', ' Apple iPhone 5s'));
Exercise - 1 : Function
Problem Statement:

Consider the below requirement of the Mobile Cart application:

Design the below screen:

On click of the mobile name, it should navigate to the next screen as below:

To implement this, make the click event handler function to accept productName and productId as parameters.
Define an arrow function inside the event handler to filter the product array with the selected product object using the
productId received by the function. Pass the selected product object to the next screen.
[Hint: Use localStorage to store the product object as below:
localStorage.setItem("Product",JSON.stringify(filteredList[0]));
Here filteredList is the array holding the selected product object which needs to be converted to string representation using
JSON.stringify function, so that you can access the properties in the next page.
In the ProductDetail page, get the selected product object from the localStorage as below:
let Product=JSON.parse(localStorage.getItem("Product"));
]
Write a TypeScript code to solve the above requirement. The Complete HTML code is given below:
HomePage.html:
<!doctype html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.navbar-inverse {
background-color: #005580;
background-image: none;
background-repeat: no-repeat;
lOMoARcPSD|37346256

color: #ffffff;
}
.navbar-inverse .navbar-nav>.active>a {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav>li>a:hover {
text-decoration: none;
color: #ffffff;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
</ul>
<!--/.nav-collapse -->
<ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
<li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart" style="color:white"></span></a>
</li>
</ul>
</div>
</nav>
<div style="margin-top:7%">
<center>
<h2>Your Favorite Online Mobile Shop!</h2>
</center>
</div>
<div class="container" style="padding-top:5%">
<div class="row">
<div class="col-md-4">
<div style="text-align: center;">
<img src="images/SamsungGalaxy_Gold.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails();" style="cursor:pointer;color:Steelblue;text-align: center;">
<b><span id="pName0">Samsung Galaxy Note 7</span></b></div>
<div style="padding-top:10px;padding-left: 101px;"> <b> Price:</b> &nbsp; &dollar; <span
id="pPrice0">699</span></div>
<div style="padding-left: 100px;"><b>Status:</b><span id="pAvailable0"> Available</span></div>
</div>
</div>
<div class="col-md-4">
<div style="text-align: center;">
<img src="images/samsung_edge_silver.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails('samsungedge',231);"
style="cursor:pointer;color:Steelblue;text-align: center;"><b><span id="pName1">Samsung Galaxy
S6 Edge</span></b></div>
<div style="padding-top:10px;padding-left: 95px;"><b>Price:</b>&nbsp; &dollar;<span
id="pPrice1">630</span></div>
<div style="padding-left: 94px;"><b>Status:</b><span id="pAvailable1"> Available </span></div>
</div>
</div>
lOMoARcPSD|37346256

<div class="col-md-4">
<div style="text-align: center;">
<img src="images/lumia_640xl.jpg" height="250px">
</div>
<div style="padding-top:10px;">
<div onclick="getMobileDetails('lumia',875);"
style="cursor:pointer;color:Steelblue;text-align: center; "><b><span id="pName2">Nokia Lumia
640XL</span></b></div>
<div style="padding-top:10px;padding-left: 118px;"><b>Price:</b>&nbsp;&dollar;<span
id="pPrice2">224</span></div>
<div style="padding-left: 117px;"><b>Status:</b><span id="pAvailable2">Out of Stock!</span></div>
</div>
</div>
</div>
</div>
</body>
<!-- Adding the converted js file -->
<script src="productlist.js"></script>
</html>
Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.
ProductDetail.html:
<!doctype html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
.navbar-inverse {
background-color: #005580;
background-image: none;
background-repeat: no-repeat;
color: #ffffff;
}
.navbar-inverse .navbar-nav>.active>a {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav>li>a:hover {
text-decoration: none;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="Index.html">Home</a></li>
</ul>
<!--/.nav-collapse -->
<ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
<li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart" style="color:white"></span></a>
</li>
</ul>
</div>
</nav>
lOMoARcPSD|37346256

<div class="container" style="margin-top:7%">


<div class="row">
<div class="col-sm-4">
<div style="margin-left:40%;padding-top:15px;">
<div style="padding:15px;">
<div>
<img id="phoneImage" src="Images/Part 1/SamsungGalaxy_Gold.JPG" height="250px">
</div>
<div style="padding-top:10px;">
<div><b><span id="pName"></span></b></div>
<div style="padding-top:10px;"><b>Price:</b>&nbsp;&dollar;<span id="pPrice"></span></div>
<div><b>Status:</b>&nbsp;<span id="pAvailable"></span></div>
<div><b class="text-danger">Discount:</b>&nbsp;<span id="pDiscount"></span></div>
</div>
</div>
</div>
</div>
<div></div>
<div style="padding-top:15px;">
<div>
<img src="Images/Part 1/goldmobile.png" style="padding-left:15px;cursor:pointer;"
onclick="getMobileByColor('gold');">
<img src="Images/Part 1/pinkmobile.png" style="cursor:pointer;padding-left:15px;"
onclick="getMobileByColor('pink');">
<img src="Images/Part 1/silvermobile.png" style="cursor:pointer;padding-left:15px;"
onclick="getMobileByColor('silver');">
</div>
<div style="padding-top:10px;">
<span style="padding-left:20px;">
GoldPlatinum
</span>
<span style="padding-left:38px;">
PinkGold
</span>
<span style="padding-left:40px;">
SilverTitanium
</span>
</div>
<div style="padding-top:10px;">
<span style="padding-left: 20px;">&dollar;</span><span id="gold" style="padding-left: 2px;"></span>
<span style="padding-left: 90px;">&dollar;</span><span id="pinkgold"
style="padding-left: 2px;"></span>
<span style="padding-left: 65px;">&dollar;</span><span id="silver"
style="padding-left: 2px;"></span>
<div id="productDescription" style="padding-top:5%;width:70%;text-align:justify">
Samsung Galaxy Note 7 is a stylish mobile you can ever have. It has 64GB memory.
</div>
<div style="padding-top:5%;padding-right:10%">
<button class="btn btn-success" onclick="addtoCart();">Add to Cart</button>
<a style="padding-left:10px;" onclick="backHome();">Back</a>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Adding converted js code-->
<script src="productdetail.js"></script>
</htmlAttach the transpiled TypeScript file to the HTML page as highlighted in the above code.

Modify the event handler function to make productId as optional parameter and productName as default parameter (Samsung
Galaxy Note7)
Download the additional images to be used in the exercise application.>
Exercise - 2 : Function
Problem Statement:
lOMoARcPSD|37346256

In the previous example we have navigated from the home page to the product detail page given below:

In this page, on click of each color, the corresponding mobile image, and price have to be updated on the screen.

Example: On click of PinkGold the below screen should be rendered:

Write an event handler that accepts color as the string parameter. Depending on the color value update the product details.
The image and price of the product should be changed based on the color which has been clicked.

Below is the complete HTML code, write TypeScript code to solve the requirement.

ProductDetail.html
<!doctype html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
.navbar-inverse {
background-color: #005580;
background-image: none;
background-repeat: no-repeat;
color: #ffffff;
}
.navbar-inverse .navbar-nav>.active>a {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav>li>a:hover {
text-decoration: none;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
lOMoARcPSD|37346256

<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="Index.html">Home</a></li>
</ul>
<!--/.nav-collapse -->
<ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
<li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart" style="color:white"></span></a>
</li>
</ul>
</div>
</nav>
<div class="container" style="margin-top:7%">
<div class="row">
<div class="col-sm-4">
<div style="margin-left:40%;padding-top:15px;">
<div style="padding:15px;">
<div>
<img id="phoneImage" src="Images/Part 1/SamsungGalaxy_Gold.JPG" height="250px">
</div>
<div style="padding-top:10px;">
<div><b><span id="pName"></span></b></div>
<div style="padding-top:10px;"><b>Price:</b>&nbsp;&dollar;<span id="pPrice"></span></div>
<div><b>Status:</b>&nbsp;<span id="pAvailable"></span></div>
<div><b class="text-danger">Discount:</b>&nbsp;<span id="pDiscount"></span></div>
</div>
</div>
</div>
</div>
<div></div>
<div style="padding-top:15px;">
<div>
<img src="Images/Part 1/goldmobile.png" style="padding-left:15px;cursor:pointer;"
onclick="getMobileByColor('gold');">
<img src="Images/Part 1/pinkmobile.png" style="cursor:pointer;padding-left:15px;"
onclick="getMobileByColor('pink');">
<img src="Images/Part 1/silvermobile.png" style="cursor:pointer;padding-left:15px;"
onclick="getMobileByColor('silver');">
</div>
<div style="padding-top:10px;">
<span style="padding-left:20px;">
GoldPlatinum
</span>
<span style="padding-left:38px;">
PinkGold
</span>
<span style="padding-left:40px;">
SilverTitanium
</span>
</div>
<div style="padding-top:10px;">
<span style="padding-left: 20px;">&dollar;</span><span id="gold" style="padding-left: 2px;"></span>
<span style="padding-left: 90px;">&dollar;</span><span id="pinkgold"
style="padding-left: 2px;"></span>
<span style="padding-left: 65px;">&dollar;</span><span id="silver"
style="padding-left: 2px;"></span>
<div id="productDescription" style="padding-top:5%;width:70%;text-align:justify">
Samsung Galaxy Note 7 is a stylish mobile you can ever have. It has 64GB memory.
</div>
<div style="padding-top:5%;padding-right:10%">
<button class="btn btn-success" onclick="addtoCart();">Add to Cart</button>
<a style="padding-left:10px;" onclick="backHome();">Back</a>
lOMoARcPSD|37346256

</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Adding converted js code-->
<script src="productdetail.js"></script>
</html>
Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.
Why Interface?

Interfaces can be used to impose consistency among various TypeScript classes.


Any class which implements an interface should implement all the required members of that interface.
Interfaces can be used to ensure that proper values are being passed into functions, properties as well as constructors.
Interfaces can be used to achieve additional flexibility as well as loosely coupling in an application.
Any object which implements an interface can be passed as a parameter to a function whose parameter type is declared the
same as the interface.
Consider the below screen of the Mobile Cart application:

Here an array is used to store the product information. But not restricted the type of object to be stored in the array. You can
restrict the array which contains only a particular type of object. For this, use Interface.

Let us discuss more on Interface in TypeScript.


What is an Interface?
An interface in TypeScript is used to define contracts within the code.
 Interfaces are used to enforce type checking by defining contracts.
 It is a collection of properties and method declarations.
 Interfaces are not supported in JavaScript and will get removed from the generated JavaScript.
 Interfaces are mainly used to identify issues upfront as we proceed with coding.
How to create an Interface?
lOMoARcPSD|37346256

Tryout : How to create an Interface


Problem Statement
Consider that a developer needs to declare an interface named - Product with two properties like productId and productName
with a number and string datatype and need to implement logic to populate the Product details using this interface then this
code-snippet would work fine.
Activity:

 Modify line no 13 as given below and re-execute the code.


let prodObject={productName:'Mobile', productPrice:10000};

 Replace the below-mentioned code at line no 13 and modify line no 9 to populate all the details of the Product onto
the console.
let prodObject={productId: 1001, productName:'Mobile', productPrice:10000};
code in TypeScript
// declaring an interface
interface Product {
productId: number ;
productName: string ;
}

// logic to display the Product details with interface object as parameter


function getProductDetails(productobj: Product): string {
return 'The product name is : ' + productobj.productName;
}

// declaring a variable having interface properties


const prodObject = {productId: 1001, productName: 'Mobile'};

// declaring variable and invoking Product details function


const productDetails: string = getProductDetails(prodObject);

// line to populate the created product on console


console.log(productDetails);
Duck Typing
Duck-Typing is a rule for checking the type compatibility for more complex variable types.

TypeScript compiler uses the duck-typing method to compare one object with the other by comparing that both the objects
have the same properties with the same data types.

TypeScript interface uses the same duck typing method to enforce type restriction. If an object that has been assigned as an
interface contains more properties than the interface mentioned properties, it will be accepted as an interface type and
additional properties will be ignored for type checking

Let us rewrite the previous example to a pass additional parameter.


lOMoARcPSD|37346256

Tryout : Duck Typing


Problem Statement
Consider that a developer needs to declare an interface named - Product with two properties like productId and productName
with the number and string datatype and need to implement logic to populate the Product details using this interface then this
code-snippet would work fine.

Activity:

Comment lines 3 and 4 and re-execute the code.

Add one more property as productCategory into the declared Product interface and display all the Product details on the
console.
Code in TypeScript

// declaring an interface
interface Product {
productId: number;
productName: string;
}

// logic to display the Product details with interface object as parameter


// tslint:disable-next-line:adjacent-overload-signatures
function getProductDetails(productobj: Product): string {
return 'The product name is : ' + productobj.productName;
}
// declaring a variable along with interface properties
const prodObject = {productId: 1001, productName: 'Mobile', productCategory: 'Gadget'};
// declaring variable and invoking Product details function
const productDetails: string = getProductDetails(prodObject);
// line to populate the created product variable on console
console.log(productDetails);
Defining an Interface
Interface keyword is used to declare an interface.

An interface should have properties and method declarations.

Properties or methods in an interface should not have any access modifiers.

Properties cannot be initialized in a TypeScript interface.

Defining an Interface – Optional Property


In a TypeScript interface, if certain properties need to be made optional, you can make them optional by adding ‘?’ after the
property name.

Let us rewrite the duck typing example with the optional property.
lOMoARcPSD|37346256

Tryout : Interfaces Optional Property


Problem Statement
Consider that a developer needs to declare an interface named - Product with two properties like productId and productName
with a number and string datatype, where productId should be declared as an optional parameter and need to implement logic
to populate the Product details using this interface then this code-snippet would work fine.
Activity:

 Add one more property as productCategory as an optional parameter into the declared Product interface and
display all the Product details on the console.

Code in TypeScript
// declaring an interface with optional parameter
interface Product {
productId?: number;
productName: string;
}
// logic to display the Product details with interface object as parameter
function getProductDetails(productobj: Product): string {
return 'The product name is ' + productobj.productName;
}

// declaring a variable along with interface properties


const prodObject = {productName: 'Mobile', productCategory: 'Gadget'};
// declaring variable and invoking Product details function
const productDetails: string = getProductDetails(prodObject);
// line to populate the created product variable on console
console.log(productDetails);

Function Types

Interfaces can be used to define the structure of functions like defining structure of objects.

Once the interface for a function type is declared, you can declare variables of that type and assign functions to the
variable if the function matches the signature defined in the interface.

Function type interface is used to enforce the same number and type of parameters to any function which is been
declared with the function type interface.

Tryout : Function Types


Problem Statement

Consider that a developer needs to declare an interface with function type and access its value below mentioned code-snippet
would work fine.
Activity:
lOMoARcPSD|37346256

 Modify the line no 8 as below mentioned and re-execute the code.


(chars: string): string;

 Add below mentioned code at line no 19 and populate the respective details after line no 21.
let id2: string = IdGenerator("Mr.Sam", 102);

Code in TypeScript
// declaring a function
function CreateCustomerID(name: string, id: number): string {
return 'The customer id is ' + name + ' ' + id;
}
// declaring a interface with function type
interface StringGenerator {

(chars: string, nums: number): string;


}
// creating reference variable of above declared interface
let idGenerator: StringGenerator;
// assignment of function to interface reference variable
idGenerator = CreateCustomerID;
// declaring a string parameter to hold return value of function type interface
const customerId: string = idGenerator('Mr.Tom', 101);
// line to populate the Customer Details
console.log(customerId);

Extending Interfaces
An interface can be extended from an already existing one using the extends keyword.
In the code below, extend the productList interface from both the Category interface and Product interface.

Tryout : Extending Interfaces


Problem Statement
Consider that a developer needs to declare a productList interface which extends properties from two other declared
interfaces like Category,Product as well as implementation to create a variable of this interface type.
Activity:
 Comment line nos 20 and 21 and re-execute the code.
 Declare one more variable of type productList interface and populate its details on console.

Code in TypeScript
// declaring a Category interface
interface Category {
categoryName: string;
}
// declaring a Product interface
interface Product {
productName: string;
productId: number;
}
// declaring a ProductList interface which is extends from Category and Product interfaces
interface ProductList extends Category, Product {
list: Array<string>;
}

// declaring a variable which is type of ProductList interface


lOMoARcPSD|37346256

const productDetails: ProductList = {


categoryName: 'Gadget',
productName: 'Mobile',
productId: 1234,
list: ['Samsung', 'Motorola', 'LG']
};

// assigning list value of productDetails variable into another variable


const listProduct = productDetails.list;
// assigning productName value of productDetails variable into another variable
const pname: string = productDetails.productName;
// line to populate Product name
console.log('Product Name is ' + pname);
// line to populate Product list
console.log('Product List is ' + listProduct);

Class Types
Make use of the interface to define class types to explicitly enforce that a class meets a particular contract. Use implements
keyword to implement interface inside a class.
To enforce interface type on a class, while instantiating an object of a class declare it using the interface type.
The only interface declared functions and properties will be available with the instantiated object.

Tryout : Class Types

Problem Statement
Consider that a developer needs to declare a class named Gadget which implements the two methods named -
getProductDetails and displayProductName from a Product interface and consists of its own method named getGadget as
well as displays the Product name on console.
Activity:
 Comment line no 4 and re-execute the code.
 Create a variable named productDetails and hold return value of getProductDetails method and populate the details
on console.
Code in TypeScript
// declaring a Product interface
interface Product {
displayProductName: (prouctId: number) => string;
getProductDetails(): string[];
}
// declaring Gadget class which implements Product interface
class Gadget implements Product {
getProductDetails(): string[] {
return ['Samsung', 'LG', 'Moto'];
}
displayProductName(productId: number): string {
if (productId === 101) {
return 'Product Name is Mobile';
} else if ( productId === 201) {
return 'Product Name is Tablet';
}
}
getGadget(): string[] {
return ['Mobile', 'Tablet', 'iPad', 'iPod'];
}
}
lOMoARcPSD|37346256

// creating instance of class of interface type


const gadget: Product = new Gadget();
// creating variable to hold return value of displayProductName function
const productName: string = gadget.displayProductName(101);
// line to populate Product name on console
console.log(productName);
Exercise : Interface
Problem Statement:
Consider the below screen of the Mobile Cart application which you have designed in the previous exercise:

The product array objects used in this example are not restricted to a specific type. Restrict the objects of the product array to
a specific Interface type.
The object must have the below properties:
pId:number;
productName: string;
productPrice: number;
productAvailable: boolean;
imageUrl:string;
productDescription:string;
Update the TypeScript code with the above requirement and render it in the HTML page.
The complete HTML code is given below:
1. <!doctype html>
1. <html>
2. <head>
3. <title>Mobile Cart</title>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1">
6. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
7. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
8. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
9. <style>
10. .navbar-inverse {
11. background-color: #005580;
12. background-image: none;
13. background-repeat: no-repeat;
14. color: #ffffff;
15. }
16. .navbar-inverse .navbar-nav>.active>a {
17. color: #ffffff;
18. background-color: transparent;
19. }
20. .navbar-inverse .navbar-nav>li>a:hover {
21. text-decoration: none;
22. color: #ffffff;
23. }
24. </style>
25. </head>
26. <body>
27. <nav class="navbar navbar-inverse navbar-fixed-top">
28. <div class="navbar-header">
29. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
30. aria-expanded="false" aria-controls="navbar">
31. <span class="sr-only">Toggle navigation</span>
32. <span class="icon-bar"></span>
33. <span class="icon-bar"></span>
lOMoARcPSD|37346256

34. <span class="icon-bar"></span>


35. </button>
36. <a class="navbar-brand" href="#">Mobile Cart</a>
37. </div>
38. <div id="navbar" class="collapse navbar-collapse">
39. <ul class="nav navbar-nav">
40. <li><a href="#">Home</a></li>
41. </ul>
42. <!--/.nav-collapse -->
43. <ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
44. <li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart" style="color:white"></span></a>
45. </li>
46. </ul>
47. </div>
48. </nav>
49. <div style="margin-top:7%">
50. <center>
51. <h2>Your Favorite Online Mobile Shop!</h2>
52. </center>
53. </div>
54. <div class="container" style="padding-top:5%">
55. <div class="row">
56. <div class="col-md-4">
57. <div style="text-align: center;">
58. <img src="images/SamsungGalaxy_Gold.jpg" height="250px">
59. </div>
60. <div style="padding-top:10px;">
61. <div onclick="getMobileDetails();" style="cursor:pointer;color:Steelblue;text-align: center;">
62. <b><span id="pName0">Samsung Galaxy Note 7</span></b></div>
63. <div style="padding-top:10px;padding-left: 101px;"><b>Price:</b>&nbsp;&dollar;<span
64. id="pPrice0">699</span></div>
65. <div style="padding-left: 100px;"><b>Status:</b><span id="pAvailable0">Available</span></div>
66. </div>
67. </div>
68. <div class="col-md-4">
69. <div style="text-align: center;">
70. <img src="images/samsung_edge_silver.jpg" height="250px">
71. </div>
72. <div style="padding-top:10px;">
73. <div onclick="getMobileDetails('samsungedge',231);"
74. style="cursor:pointer;color:Steelblue;text-align: center;"><b><span id="pName1">Samsung Galaxy
75. S6 Edge</span></b></div>
76. <div style="padding-top:10px;padding-left: 95px;"><b>Price:</b>&nbsp;&dollar;<span
77. id="pPrice1">630</span></div>
78. <div style="padding-left: 94px;"><b>Status:</b><span id="pAvailable1">Available</span></div>
79. </div>
80. </div>
81. <div class="col-md-4">
82. <div style="text-align: center;">
83. <img src="images/lumia_640xl.jpg" height="250px">
84. </div>
85. <div style="padding-top:10px;">
86. <div onclick="getMobileDetails('lumia',875);"
87. style="cursor:pointer;color:Steelblue;text-align: center; "><b><span id="pName2">Nokia Lumia
88. 640XL</span></b></div>
89. <div style="padding-top:10px;padding-left: 118px;"><b>Price:</b>&nbsp;&dollar;<span
90. id="pPrice2">224</span></div>
91. <div style="padding-left: 117px;"><b>Status:</b><span id="pAvailable2">Out of Stock!</span></div>
92. </div>
93. </div>
94. </div>
95. </div>
96. </body>
97. <!-- Adding the converted js file -->
98. <script src="productlist.js"></script>
99. </html>
Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.
lOMoARcPSD|37346256

Why Class?

Classes are used to create reusable components. Till the ES5 version of JavaScript, you do not have a class concept as
such. For implementing reusable components, use functions and prototype-based inheritance. TypeScript provides an option
for the developers to use object-oriented programming with the help of classes.
In the Mobile Cart application, you can use a class to define the product and create various objects of different products. In
the below screen, creating different objects of product and rendering the details

Let us discuss more on classes in TypeScript.


What is a Class?
 Class is a template from which objects can be created.
 It provides behavior and state storage.
 It is meant for implementing reusable functionality.
 Use a class keyword to create a class.

Constructor
A constructor is a function that gets executed automatically whenever an instance of a class is created using a new keyword.
 To create a constructor, a function with the name as a "constructor" is used.
 A class can hold a maximum of one constructor method per class.
 You can use optional parameters with a constructor function as well.

Tryout : Constructor
Problem Statement
Consider that a developer needs to declare a class named - Product with the below-mentioned declarations:
productId as number property

Constructor to initialize this value


getProductId method to return the message "Product id is <<id value>>".
Activity:
Create another object of Product class after line no 15 and populate its details on console.
lOMoARcPSD|37346256

Modify the declared Product class by adding another property named productPrice of number datatype, declare a method
named getProductPrice, and with the help of product object, you need to populate the message "Product price is << value>>"
on the console.
Code in TypeScript
// declaring a Product class
class Product {
static productPrice: string;
productId: number;
// constructor declaration
constructor(productId: number) {
this.productId = productId;
}
getProductId(): string {
return 'Product id is : ' + this.productId;
}
}
// creation of Product class object
const product: Product = new Product(1234);
// line to populate the product id details
console.log(product.getProductId());
Access Modifiers
Access modifiers are used to provide certain restriction of accessing the properties and methods outside the class.

Public and Private Access Modifiers

Protected Access Modifier

Static Access Modifier


TypeScript provides an option to add a static keyword. This keyword can be used to declare a class variable or method.
A static variable belongs to the class and not to the instance of the class.
A variable or function declared with a static keyword can be accessed using the class name instead of the instance of the
class.
Static variables are initialized only once, at the start of the execution.
A single copy of the static variables would be shared by all instances of the class.
lOMoARcPSD|37346256

A static variable can be accessible inside the static function as well as the non-static function.
A static function can access only static variables and other static functions.

Tryout : Access Modifiers


Problem Statement
Consider that a developer needs to create a Product class with 4 properties namely productId, productName, productPrice,
productCategory with private, public, static, and protected access modifiers and accessing them through Gadget class and its
methods.

Activity:

 Modify the line nos 5 and 6 as given below and re-execute the code.
productPrice: number=150;
private productCategory: string;

 Create another object of Gadget class and populate the product id details on the console.
Code in TypeScript
// declaring a Product class with access modifiers
class Product {
static productPrice = 150;
private productId: number;
public productName: string;
protected productCategory: string;
// declaration of constructor with 3 parameters
constructor(productId: number, productName , productCategory) {
this.productId = productId;
this.productName = productName;
this.productCategory = productCategory;
}
// method ot display product id details
getProductId() {
console.log('The Product id is : ' + this.productId);
}
}
// declaring a Gadget class extending the properties from Product class
class Gadget extends Product {
// method to display productCategory property
getProduct(): void {
console.log('Product category is : ' + this.productCategory);
}
}
// Gadget Class object creation
const g: Gadget = new Gadget(1234, 'Mobile', 'SmartPhone');
// invoking getProduct method with the help of Gadget object
g.getProduct();

// invoking getProductId method with the help of Gadget object


g.getProductId();

// line to populate product name property with Gadget object


console.log('Product name is : ' + g.productName);

// line to populate static property product price directly with Product class name
console.log('Product price is : $' + Product.productPrice);
Properties and Methods – Parameter Properties
lOMoARcPSD|37346256

Instead of declaring instance variables and then passing parameters to the constructor and initializing it, you can reduce the
code by adding access specifiers to the parameters passed to the constructor.
Consider the below code:

Instead of this declare the parameter itself with any of the access modifiers and reduce the lines of code used for the
initialization.
Let us rewrite the above code:

Properties and Methods- Accessors


TypeScript provides an option to add getters/setters to control accessing the members outside the class or modifying the
same.
There is no direct option available to access private members outside the class but use accessors in TypeScript for the same.
If you need to access private properties outside the class, you can use the getter and if you need to update the value of the
private property, you can use the setter.

Demo : Accessors
Highlights:
 Creating accessors in a class
 Accessing accessors
Demo steps:
Step 1: Create a file class_accessors.ts

1. let passcode = "secret passcode";


1. class Product {
2. private _productName: string;
3. get productName(): string {
4. return this._productName;
5. }
6. set productName(newName: string) {
7. if (passcode && passcode == "secret passcode") {
8. this._productName= newName;
9. }
10. else {
lOMoARcPSD|37346256

11. console.log("Error: Unauthorized update of employee!");


12. }
13. }
14. }
15. let product:Product = new Product();
16. product.productName = "Fridge";
17. if (product.productName) {
18. console.log(product.productName);
19. }

Step 2: Open a command prompt and navigate to the folder in which interface.ts file resides and run tsc class_accessors.ts

Step 3: Run node class_accessors.js from the command line

Inheritance
Extending Classes with Inheritance
Inheritance is the process of extending a class from an already existing class and reuse the functions and properties of the
inherited class in the subclass.
TypeScript supports inheritance with class, wherein the superclass functionalities can be reused within the subclass.
The subclass constructor function definition should invoke the superclass constructor using the super function.

Use the super keyword to access the methods of the super class inside the subclass methods.
Override the superclass methods inside the subclass by specifying the same function signature.

Tryout : Inheritance
Problem Statement
Consider that a developer needs to create Product class with productId number type variable and with getProduct method to
display the message "Product id is <<value>>" and then create another class named Gadget extending Product class with a
constructor and a method named getProduct() to access the properties of the inherited class.

Activity:

Modify line no 3 as given below and re-execute the code.

Comment line nos 14 and 17 and re-execute the code.

Create an object of Product and invoke the getProduct() of that class.


Code in TypeScript
// declaring Product class
class Product {
protected productId: number;
constructor(productId: number) {
this.productId = productId;
}
lOMoARcPSD|37346256

getProduct(): void {
console.log('Product id is : ' + this.productId);
}}

// declaring Gadget class which extends properties from Product class


class Gadget extends Product {
constructor(public productName: string , productId: number ) {
super(productId);
}
getProduct(): void {
super.getProduct();
console.log('Product id is : ' + this.productId + ' Product name is : ' + this.productName);
}
}

// Gadget class object creation


const g = new Gadget('Tablet', 1234);

// line to invoke getProduct method with the help of Gadget object


g.getProduct();
Abstract Class
 Abstract classes are base classes that may not be instantiated.
 An abstract class can be created using abstract keyword.
 Abstract methods within an abstract class are methods declared with abstract keyword and does not contain
implementation.
 They must be implemented inside the derived classes.
 Abstract classes can contain both abstract methods and its implementations.

Tryout : Abstract Class


Problem Statement
Consider that a developer needs to create three classes named - Product, Gadget and Clothing where Gadget and Clothing are
extending the method - getProductName from abstract class - Product and implementing the logic of invoking
getProductName method with non-abstract class object.

Activity:

Modify the line no 6 as given below and re-execute the code.


getProductName():string;

Create another object of Gadget and invoke getFeatures method to display a message "This product has camera features" on
console.
Code in TypeScript
// abstract class Product declaration
abstract class Product {
getFeatures(): string {
return;
}
lOMoARcPSD|37346256

abstract getProductName(): string;


}

// declaring Gadget class extending abstract class Product


class Gadget extends Product {
getProductName(): string {
return 'Product name is Mobile';
}

getFeatures(): string {
return 'This product has camera feature';
}
}

// declaring Clothing class extending abstract class Product


class Clothing extends Product {
getProductName(): string {
return 'Product name is Shirt';
}
}

// Gadget class object creation


const g = new Gadget();

// line to invole getProductName() through Gadget object


console.log(g.getProductName());
console.log(g.getFeatures());
// Clothing class object creation
const c = new Clothing();

// line to invole getProductName() through Clothing object


console.log(c.getProductName());
Exercise : Class
Problem Statement:
Consider the below screen of the Mobile Cart application which is designed in the previous exercise:

Here you have created a class using object literals. Modify the code to define a class Product and add the properties which
you have used in the Interface exercise. Create objects of the Product class and place them into the productlist array.
Update the TypeScript code with the above requirement and render it on the HTML page.
The complete HTML code is given below:

1. <!doctype html>
1. <html>
2. <head>
3. <title>Mobile Cart</title>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1">
6. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
7. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
8. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
9. <style>
10. .navbar-inverse {
11. background-color: #005580;
12. background-image: none;
lOMoARcPSD|37346256

13. background-repeat: no-repeat;


14. color: #ffffff;
15. }
16. .navbar-inverse .navbar-nav>.active>a {
17. color: #ffffff;
18. background-color: transparent;
19. }
20.
21. .navbar-inverse .navbar-nav>li>a:hover {
22. text-decoration: none;
23. color: #ffffff;
24. }
25. </style>
26. </head>
27. <body>
28. <nav class="navbar navbar-inverse navbar-fixed-top">
29. <div class="navbar-header">
30. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
31. aria-expanded="false" aria-controls="navbar">
32. <span class="sr-only">Toggle navigation</span>
33. <span class="icon-bar"></span>
34. <span class="icon-bar"></span>
35. <span class="icon-bar"></span>
36. </button>
37. <a class="navbar-brand" href="#">Mobile Cart</a>
38. </div>
39. <div id="navbar" class="collapse navbar-collapse">
40. <ul class="nav navbar-nav">
41. <li><a href="#">Home</a></li>
42. </ul>
43. <!--/.nav-collapse -->
44. <ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
45. <li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart"
style="color:white"></span></a>
46. </li>
47. </ul>
48. </div>
49. </nav>
50. <div style="margin-top:7%">
51. <center>
52. <h2>Your Favorite Online Mobile Shop!</h2>
53. </center>
54. </div>
55. <div class="container" style="padding-top:5%">
56. <div class="row">
57. <div class="col-md-4">
58. <div style="text-align: center;">
59. <img src="images/SamsungGalaxy_Gold.jpg" height="250px">
60. </div>
61. <div style="padding-top:10px;">
62. <div onclick="getMobileDetails();" style="cursor:pointer;color:Steelblue;text-align: center;">
63. <b><span id="pName0">Samsung Galaxy Note 7</span></b>
64. </div>
65. <div style="padding-top:10px;padding-left: 101px;"><b>Price:</b>&nbsp;&dollar;<span
66. id="pPrice0">699</span></div>
67. <div style="padding-left: 100px;"><b>Status:</b><span id="pAvailable0">Available</span></div>
68. </div>
69. </div>
70. <div class="col-md-4">
71. <div style="text-align: center;">
72. <img src="images/samsung_edge_silver.jpg" height="250px">
73. </div>
74. <div style="padding-top:10px;">
75. <div onclick="getMobileDetails('samsungedge',231);"
lOMoARcPSD|37346256

76. style="cursor:pointer;color:Steelblue;text-align: center;"><b><span id="pName1">Samsung


Galaxy
77. S6 Edge</span></b></div>
78. <div style="padding-top:10px;padding-left: 95px;"><b>Price:</b>&nbsp;&dollar;<span
79. id="pPrice1">630</span></div>
80. <div style="padding-left: 94px;"><b>Status:</b><span id="pAvailable1">Available</span></div>
81. </div>
82. </div>
83. <div class="col-md-4">
84. <div style="text-align: center;">
85. <img src="images/lumia_640xl.jpg" height="250px">
86. </div>
87. <div style="padding-top:10px;">
88. <div onclick="getMobileDetails('lumia',875);"
89. style="cursor:pointer;color:Steelblue;text-align: center; "><b><span id="pName2">Nokia Lumia
90. 640XL</span></b></div>
91. <div style="padding-top:10px;padding-left: 118px;"><b>Price:</b>&nbsp;&dollar;<span
92. id="pPrice2">224</span></div>
93. <div style="padding-left: 117px;"><b>Status:</b><span id="pAvailable2">Out of Stock!
</span></div>
94. </div>
95. </div>
96. </div>
97. </div>
98. </body>
99. <!-- Adding the converted js file -->
100. <script src="productlist.js"></script>
101. </html>

Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.

Why Modules and Namespaces? - Viewer Page | Infosys Springboard


Why Modules and Namespaces?
Modules and Namespaces

Modules and Namespaces are useful in grouping functionalities under a common name.

The main use is reusability.

Code can be reused by importing modules or namespaces in other files.

Namespaces are used for namespace resolution and are suitable for the development of a smaller application.

In larger-scale applications, they can be used to achieve modularity.

TypeScript provides native support in terms of module loaders using modules concept which takes care of all the concerns
with respect to modularity.

In the MobileCart application, create a product utility namespace or module and place the code related to the product in it.
Reuse the code related to the product by importing it into other files.

Let us discuss more on Namespace and Module in TypeScript.


What is Namespace?
A Namespace is used to group functions, classes, or interfaces under a common name.

The content of namespaces is hidden by default unless they are exported.

Use nested namespaces if required.


lOMoARcPSD|37346256

The function or any construct which is not exported cannot be accessible outside the namespace.

Creating and using Namespaces


In the below example, create a namespace called Utility and group a function MaxDiscountAllowed and a nested namespace
called payment inside it.

To import the namespace and use it, make use of the triple slash reference tag.

The file in which the namespace is declared and the file which uses the namespace to be compiled together. It is preferable to
group the output together in a single file. You have an option to do that by using the --outFile keyword.

Demo : Namespace

Highlights:
 Creating Namespace
 Accessing Namespace
Demo steps:
Step 1: Create a file namespace_demo.ts

1. namespace Utility {
1. export namespace Payment {
2. export function CalculateAmount(price: number, quantity: number): number {
lOMoARcPSD|37346256

3. return price * quantity;


4. }
5. }
6. export function MaxDiscountAllowed(noOfProduct: number): number {
7. if (noOfProduct > 5) {
8. return 40;
9. } else {
10. return 10;
11. }
12. }
13. function privateFunc(): void {
14. console.log('This is private...');
15. }
16. }

Step 2: Create another file Namespace_import.ts

1. /// <reference path="./namespace_demo.ts" />


1. import util = Utility.Payment;
2. let paymentAmount = util.CalculateAmount(1255, 6);
3. console.log(`Amount to be paid: ${paymentAmount}`);
4. let discount = Utility.MaxDiscountAllowed(6);
5. console.log(`Maximum discount allowed is: ${discount}`);

Step 3: Open Node.js command prompt, change directory to the folder in which Namespace file resides and run the below
command from the command line:

Step 4: Run node Final.js from the command line

Exercise : Namespace
Problem Statement:
Consider the below screen of the Mobile Cart application which is designed in the previous exercise:

Create a namespace called ProductUtility and place the Product class definition in it. Import the Product class inside
productlist file and use it.
Hint1: Create a new file and place the Product class code in it within ProductUtility namespace.
Hint2: Remove the Product class from the productlist file and use ///<reference> to import the Product class from the
namespace.
Update the TypeScript code with the above requirement and render it on the HTML page.
The complete HTML code is given below:

1. <!doctype html>
1. <html>
2.
3. <head>
lOMoARcPSD|37346256

4. <title>Mobile Cart</title>
5. <meta charset="UTF-8">
6. <meta name="viewport" content="width=device-width, initial-scale=1">
7. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
8. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
9. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
10. <style>
11. .navbar-inverse {
12. background-color: #005580;
13. background-image: none;
14. background-repeat: no-repeat;
15. color: #ffffff;
16. }
17.
18. .navbar-inverse .navbar-nav>.active>a {
19. color: #ffffff;
20. background-color: transparent;
21. }
22.
23. .navbar-inverse .navbar-nav>li>a:hover {
24. text-decoration: none;
25. color: #ffffff;
26. }
27. </style>
28. </head>
29.
30. <body>
31. <nav class="navbar navbar-inverse navbar-fixed-top">
32. <div class="navbar-header">
33. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
34. aria-expanded="false" aria-controls="navbar">
35. <span class="sr-only">Toggle navigation</span>
36. <span class="icon-bar"></span>
37. <span class="icon-bar"></span>
38. <span class="icon-bar"></span>
39. </button>
40. <a class="navbar-brand" href="#">Mobile Cart</a>
41. </div>
42. <div id="navbar" class="collapse navbar-collapse">
43. <ul class="nav navbar-nav">
44. <li><a href="#">Home</a></li>
45. </ul>
46. <!--/.nav-collapse -->
47. <ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
48. <li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart"
style="color:white"></span></a>
49. </li>
50. </ul>
51. </div>
52. </nav>
53. <div style="margin-top:7%">
54. <center>
55. <h2>Your Favorite Online Mobile Shop!</h2>
56. </center>
57. </div>
58. <div class="container" style="padding-top:5%">
59. <div class="row">
60. <div class="col-md-4">
61. <div style="text-align: center;">
62. <img src="images/SamsungGalaxy_Gold.jpg" height="250px">
63. </div>
64. <div style="padding-top:10px;">
65. <div onclick="getMobileDetails();" style="cursor:pointer;color:Steelblue;text-align: center;">
66. <b><span id="pName0">Samsung Galaxy Note 7</span></b>
lOMoARcPSD|37346256

67. </div>
68. <div style="padding-top:10px;padding-left: 101px;"><b>Price:</b>&nbsp;&dollar;<span
69. id="pPrice0">699</span></div>
70. <div style="padding-left: 100px;"><b>Status:</b><span id="pAvailable0">Available</span></div>
71. </div>
72. </div>
73. <div class="col-md-4">
74. <div style="text-align: center;">
75. <img src="images/samsung_edge_silver.jpg" height="250px">
76. </div>
77. <div style="padding-top:10px;">
78. <div onclick="getMobileDetails('samsungedge',231);"
79. style="cursor:pointer;color:Steelblue;text-align: center;"><b><span id="pName1">Samsung
Galaxy
80. S6 Edge</span></b></div>
81. <div style="padding-top:10px;padding-left: 95px;"><b>Price:</b>&nbsp;&dollar;<span
82. id="pPrice1">630</span></div>
83. <div style="padding-left: 94px;"><b>Status:</b><span id="pAvailable1">Available</span></div>
84. </div>
85. </div>
86. <div class="col-md-4">
87. <div style="text-align: center;">
88. <img src="images/lumia_640xl.jpg" height="250px">
89. </div>
90. <div style="padding-top:10px;">
91. <div onclick="getMobileDetails('lumia',875);"
92. style="cursor:pointer;color:Steelblue;text-align: center; "><b><span id="pName2">Nokia Lumia
93. 640XL</span></b></div>
94. <div style="padding-top:10px;padding-left: 118px;"><b>Price:</b>&nbsp;&dollar;<span
95. id="pPrice2">224</span></div>
96. <div style="padding-left: 117px;"><b>Status:</b><span id="pAvailable2">Out of Stock!
</span></div>
97. </div>
98. </div>
99. </div>
100. </div>
101. </body>
102. <!-- Adding the converted js file -->
103. <script src="productlist.js"></script>
104. </html>

Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.

What is a Module?
Modules help us in grouping a set of functionalities under a common name. The content of modules cannot be accessible
outside unless exported.
Precede export keyword to the function, class, interface, etc.. which you need to export from a module.

Creating and using Modules


Exporting from a Module
The constructs of a module can be exported by one of the below approaches:
1. Adding an export keyword in front of a function or a class or an interface
2. Adding an export keyword to a block of statements
lOMoARcPSD|37346256

Importing a Module
Using the import keyword, you can import a module within another module or another TypeScript file. Provide the file name
as the module name while importing.
Once the module is imported, make use of the classes and other constructs exported from the module.

Also, alias names can be used while importing/exporting a module.

Compiling Module
To compile the modules and the file which is using the module, compile them together using the tsc command.

Demo : Modules
Highlights:
 Creating a module
 Importing a module
Demo steps:
Step 1: Create a file module_demo.ts

1. export function MaxDiscountAllowed(noOfProduct: number): number {


1. if (noOfProduct > 5) {
2. return 30;
3. } else {
4. return 10;
5. }
6. }
7. class Utility {
8. CalculateAmount(price: number, quantity: number): number {
9. return price * quantity;
lOMoARcPSD|37346256

10. }
11. }
12. interface Category {
13. getCategory(productId: number): string;
14. }
15. export const productName = 'Mobile';
16. export {Utility, Category};

Step 2: Create another file 2.module_import.ts

1. import { Utility as mainUtility, Category, productName, MaxDiscountAllowed } from "./module_demo";


1. const util = new mainUtility();
2. const price = util.CalculateAmount(1350, 4);
3. const discount = MaxDiscountAllowed(2);
4. console.log(`Maximum discount allowed is: ${discount}`);
5. console.log(`Amount to be paid: ${price}`);
6. console.log(`ProductName is: ${productName}`);

Step 3: Open a command prompt and navigate to the folder in which module files resides and run the below command from
the command line

Step 4: Run node 2.module_import.js from the command line

Module Formats and Loaders


Module format is the syntax that is used to define a module in JavaScript.
Modules in TypeScript can be compiled to one of the module formats given below:

Commonly we compile the modular code in TypeScript to ES2015 format by using the --module ES2015 keyword
while performing the compilation.

If none of the formats are mentioned in the compiler option, by default CommonJS module format will be the one that gets
generated while compiling modules in TypeScript.
A module loader interprets and loads a module written in a certain module format as well as helps in importing all the
dependent modules into developer working environment. At the runtime, they play a very vital role in loading and
configuring all needed dependencies modules before executing any linked module.
The most commonly used module loaders in JavaScript are:
SystemJS module loader for modules in AMD, CommonJS, UMD, or System.register format
Require.js module loader for modules in AMD format.
On-demand functionalities can be loaded by Modules, which is known as lazy loading. By using this feature while executing
our application all the declared modules are not loaded at that moment, it only loads needed modules that are needed by the
user to render the initial look of the application on the first load. Due to this concept performance of the application can be
enhanced as the initial startup time of the application automatically decreases.
Default Exports
Default export is used to export any one of the constructs such as class, interface, function, and so on from the current
module as a default one.
Default exports are handy in case you need to export a class that has almost all functionalities attached, such as javascript
library object jQuery.
Name for the default exported constructs are optional. You can assign a name to the default construct while importing it into
the other file.
As you cannot have more than one default export per module.
lOMoARcPSD|37346256

Demo : Default Exports


Highlights:
 Creating Default Exports
 Accessing Default Exports
Demo steps:
Step 1: Create a file Default_export.ts

1. export default class {


1. productName = 'Tablet';
2. getProductDetails(productId: number): string {
3. return 'ProductId is ' + productId + 'ProductName is ' + this.productName;
4. }
5. }
6. export class Utility {
7. CalculateAmount( price: number, quantity: number): number {
8. return price * quantity;
9. }
10. }

Step 2: Create another file 4.test_defaultexport.ts

1. import Product, {Utility} from './default_exprt';


1. const product = new Product();
2. const details = product.getProductDetails(1001);
3. console.log(details);
4. const util = new Utility();
5. const price = util.CalculateAmount(1300, 4);
6. console.log(`The price is ${price}`);

Step 3: Open Node.js command prompt, change directory to the folder in which module files resides and run the below
command:

Step 4: Run node 4.test_defaultexport.js from the command line

Module Vs Namespace:
lOMoARcPSD|37346256

Module Namespace
Organizes code Organizes code
Have native support with Node.js module loader. All modern
No special loader required
browsers are supported with a module loader.
ES2015 does not have a Namespace concept. It is mainly
Supports ES2015 module syntax
used to prevent global namespace pollution.
Suited for large-scale applications Suited for small-scale applications
Exercise : Modules
Problem Statement - 1:

Consider the below screen of the Mobile Cart application which is designed as part of the previous exercise of the function
module:

On click of the AddtoCart button navigate to the screen below:

On the click event handler function, get the productId, productName, and productPrice properties of the current object stored
in the localStorage.

Create a quantity variable with an initial value of 1.

Calculate the total price of the product using the quantity and price values and assign it to a totalPrice variable.

Create selectedItem object with the properties productId, productName, price, quantity, and totalPrice, each time when the
product is added to the cart.

Maintain a local array where the selectedItem objects can be pushed. While pushing an item, if the productId of the item to
be pushed is already available in the array then instead of pushing, increment the quantity field of the existing object in the
array.

Store this object in localStorage, so that you can read it on the Cart page.

In the Cart page, populate the data from the ProductDetail page and create a dynamic table and display the details as given in
the Cart page screen above.

Write the TypeScript code to solve the above requirement. The complete HTML code is given below:

ProductDetail.html

1. <!doctype html>

1. <html>
2. <head>
3. <title>Mobile Cart</title>
lOMoARcPSD|37346256

4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1">
6. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
7. <style>
8. .navbar-inverse {
9. background-color:#005580;
10. background-image: none;
11. background-repeat: no-repeat;
12. color:#ffffff;
13. }
14. .navbar-inverse .navbar-nav > .active > a {
15. color: #ffffff;
16. background-color:transparent;
17. }
18. .navbar-inverse .navbar-nav > li > a:hover{
19. text-decoration: none;
20. }
21. </style>
22. </head>
23. <body>
24. <nav class="navbar navbar-inverse navbar-fixed-top">
25. <div class="navbar-header">
26. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-
expanded="false" aria-controls="navbar">
27. <span class="sr-only">Toggle navigation</span>
28. <span class="icon-bar"></span>
29. <span class="icon-bar"></span>
30. <span class="icon-bar"></span>
31. </button>
32. <a class="navbar-brand" href="#">Mobile Cart</a>
33. </div>
34. <div id="navbar" class="collapse navbar-collapse">
35. <ul class="nav navbar-nav">
36. <li ><a href="Index.html">Home</a></li>
37. </ul>
38. <!--/.nav-collapse -->
39. <ul class="nav navbar-nav navbar-middle" style="color:white; margin-right:30px;">
40. <li><a href="Cart.html"><span class="glyphicon glyphicon-shopping-cart"
style="color:white"></span></a></li>
41. </ul>
42. </div>
43. </nav>
44. <div class="container" style="margin-top:7%">
45. <div class="row">
46. <div class="col-sm-4">
47. <div style="margin-left:40%;padding-top:15px;">
48. <div style="padding:15px;">
49. <div>
50. <img id="phoneImage" src ="Images/Part 1/SamsungGalaxy_Gold.JPG" height="250px" >
51. </div>
52. <div style="padding-top:10px;">
53. <div><b><span id="pName"></span></b></div>
54. <div style="padding-top:10px;"><b>Price:</b>&nbsp;&dollar;<span id="pPrice"></span></div>
55. <div><b>Status:</b>&nbsp;<span id="pAvailable"></span></div>
56. <div><b class="text-danger">Discount:</b>&nbsp;<span id="pDiscount"></span></div>
57. </div>
</div>
58. </div>
59. </div>
60. <div></div>
61. <div style="padding-top:15px;">
62. <div>
63. <img src ="Images/Part 1/goldmobile.png" style="padding-left:15px;cursor:pointer;"
onclick="getMobileByColor('gold');" >
lOMoARcPSD|37346256

64. <img src ="Images/Part 1/pinkmobile.png" style="cursor:pointer;padding-left:15px;"


onclick="getMobileByColor('pink');" >
65. <img src ="Images/Part 1/silvermobile.png" style="cursor:pointer;padding-left:15px;"
onclick="getMobileByColor('silver');" >
66.
67. </div>
68. <div style="padding-top:10px;">
69. <span style="padding-left:20px;">
70. GoldPlatinum
71. </span>
72. <span style="padding-left:38px;">
73. PinkGold
74. </span>
75. <span style="padding-left:40px;">
76. SilverTitanium
77. </span>
78. </div>
79. <div style="padding-top:10px;">
80. <span style="padding-left: 20px;">&dollar;</span><span id="gold" style="padding-left: 2px;"></span>
81. <span style="padding-left: 90px;">&dollar;</span><span id="pinkgold" style="padding-left: 2px;"></span>
82. <span style="padding-left: 65px;">&dollar;</span><span id="silver" style="padding-left: 2px;"></span>
83. <div id="productDescription" style="padding-top:5%;width:70%;text-align:justify">
84. Samsung Galaxy Note 7 is a stylish mobile you can ever have. It has 64GB memory.
85. </div>
86. <div style="padding-top:5%;padding-right:10%">
87. <button class="btn btn-success" onclick="addtoCart();">Add to Cart</button>
88. <a style="padding-left:10px;" onclick="backHome();">Back</a>
89. </div>
90. </div>
91. </div>
92. </div>
93. </div>
94. </body>
95. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
96. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
97. <!-- Adding converted js code-->
98. <script src="productdetail.js"></script>
99. </html>

Cart.html

1. <!doctype html>

1. <html>
2. <head>
3. <title>Mobile Cart</title>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1">
6. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
7. <style>
8. .navbar-inverse {
9. background-color:#005580;
10. background-image: none;
11. background-repeat: no-repeat;
12. color:#ffffff;
13. }
14. .navbar-inverse .navbar-nav > .active > a {
15. color: #ffffff;
16. background-color:transparent;
17. }
18. .navbar-inverse .navbar-nav > li > a:hover{
lOMoARcPSD|37346256

19. text-decoration: none;


20. }
21. .panel panel-primary{
22. background-color:#005580;
23. }
24. .table {
25. width: 100%;
26. max-width: 100%;
27. }
28. </style>
29. </head>
30. <body onload="pageOnload();">
31. <nav class="navbar navbar-inverse navbar-fixed-top">
32. <div class="navbar-header">
33. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-
expanded="false" aria-controls="navbar">
34. <span class="sr-only">Toggle navigation</span>
35. <span class="icon-bar"></span>
36. <span class="icon-bar"></span>
37. <span class="icon-bar"></span>
38. </button>
39. <a class="navbar-brand" href="#">Mobile Cart</a>
40. </div>
41. <div id="navbar" class="collapse navbar-collapse">
42. <ul class="nav navbar-nav">
43. <li ><a href="Index.html">Home</a></li>
44. </ul>
45. <!--/.nav-collapse -->
46. </div>
47. </nav>
48. <div class="panel panel-primary"
49. style="position: relative; top: 100px; left: 350px; width: 53%" id="cart">
50. <div class="panel-heading">MobileCart</div>
51. <div class="panel-body">
52. <table class="table" id="cartTable" style="margin-left: 90px; width: auto; margin-bottom: 0px; margin-right:
0px">
53. <thead>
54. <tr style="color: blue">
55. <th>Product</th>
56. <th>Quantity</th>
57. <th>Price</th>
58. <th>Total Price</th>
</tr>
59. </thead>
60. <tbody>
61. </tbody>
62. </table>
63. </div>
64. <div class="panel-footer">
65. <button type="button" class="btn btn-default" onclick="backProduct();"
66. style="color: #ff0080;margin-left: 150px;">
67. <span class="glyphicon glyphicon-shopping-cart"></span> Continue
68. Shopping</button>
69. <button type="button" class="btn btn-success" onclick="checkOut();" >
70. Checkout <span class="glyphicon glyphicon-play"></span>
71. </button>
72. </div>
73. </div>
74. <div id="successmessage" class="panel panel-primary"
75. style="position: relative; top: 200px; left: 450px; width: 40%;display:none">
76. <div class="panel-heading">MobileCart</div>
77. <div class="panel-body">Thank you for making the payment. Your
78. order will be shipped soon...</div>
79. <div class="panel-footer">
lOMoARcPSD|37346256

80. <a class="btn btn-default" onclick="backProduct();"


81. style="color: #ff0080"> <i
82. class="glyphicon glyphicon-chevron-left"></i> Go to Products Page
83. </a>
84. </div>
85. </div>
86. </body>
87. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
88. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
89. <script src="CartData.js"></script>
90. </html>

Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.

Problem Statement - 2:

Consider the below screen of the Mobile Cart application which we have designed in the above problem statement.

In the Cart page, we have got data from the previous page and created a dynamic table, and displayed the details as given in
the Cart page screen above.

Create a SelectedProduct Interface with the below properties:

productName: string
quantity: number
price: number
totalPrice: boolean

and export it to make a module.

Modify the Cart file by importing the SelectedProduct Interface into it and restrict the type of retrieved data from the
previous page with the SelectedProduct interface.

Hint: Create a separate file with SelectedProduct Interface

On click of the Checkout button show the below screen:

On click of the GotoProductsPage button, clear the localStorage so that the content of the cart is reset and navigate to the
ProductList page.

Write the TypeScript code to solve the above requirements. The complete HTML code is given below:

Cart.html

<!doctype html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
lOMoARcPSD|37346256

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">


<style>
.navbar-inverse {
background-color:#005580;
background-image: none;
background-repeat: no-repeat;
color:#ffffff;
}
.navbar-inverse .navbar-nav > .active > a {
color: #ffffff;
background-color:transparent;

}
.navbar-inverse .navbar-nav > li > a:hover{
text-decoration: none;

}
.panel panel-primary{
background-color:#005580;
}
.table {
width: 100%;
max-width: 100%;
}
</style>
</head>
<body onload="pageOnload();">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-
expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mobile Cart</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li ><a href="Index.html">Home</a></li>

</ul>
<!--/.nav-collapse -->

</div>

</nav>
<div class="panel panel-primary"
style="position: relative; top: 100px; left: 350px; width: 53%" id="cart">
<div class="panel-heading">MobileCart</div>
<div class="panel-body">
<table class="table" id="cartTable" style="margin-left: 90px; width: auto; margin-bottom: 0px; margin-
right: 0px">
<thead>
<tr style="color: blue">
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>

</tr>

</thead>
<tbody>
lOMoARcPSD|37346256

</tbody>
</table>
</div>
<div class="panel-footer">
<button type="button" class="btn btn-default" onclick="backProduct();"
style="color: #ff0080;margin-left: 150px;">
<span class="glyphicon glyphicon-shopping-cart"></span> Continue Shopping
</button>
<button type="button" class="btn btn-success" onclick="checkOut();" >
Checkout <span class="glyphicon
glyphicon-play"></span>
</button>
</div>
</div>
<div id="successmessage" class="panel panel-primary"
style="position: relative; top: 200px; left: 450px; width: 40%;display:none">
<div class="panel-heading">MobileCart</div>
<div class="panel-body">Thank you for making the payment. Your
order will be shipped soon...</div>
<div class="panel-footer">
<a class="btn btn-default" onclick="backProduct();"
style="color: #ff0080"> <i
class="glyphicon glyphicon-chevron-left"></i> Go to Products Page
</a>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="CartData.js"></script>
</html>

Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.
Why Generics

Generics helps us to avoid writing the same code again for different data types.
In TypeScript, generics are used along :

 with function to invoke the same code with different type arguments
 with Array to access the same array declaration with a different set of typed values
 with Interface to implement the same interface declaration by different classes with different types
 with a class to access the same class with different types while instantiating it
What is Generics?

Avoid writing the same code again for different types using generics. Let us rewrite the above code using generics:
lOMoARcPSD|37346256

What are Type Parameters?


Type Parameters are used to specify the type, a generic will work over.
They are listed using an angle bracket<>.
The actual type will be provided while invoking function or instance creation.
Consider a generic function given below:

To access this function with different types you will use the below code:

Generic Array
Using Array<T>
Array<T> provides us the option to use the same array declaration for different types of data when used along with a
function.
<T> here represents the type parameter.

Tryout : Generic Array


Problem Statement
Code in TypeScript
// declaring a Generic Array named orderDetails
function orderDetails<T>(arg: Array<T>): Array<T> {
console.log(arg.length);
return arg;
}

// creating a variable to hold a number array


const orderid: Array<number> = [101, 102, 103, 104];

// creating a variable to hold a string array


const ordername: Array<string> = ['footwear', 'dress', 'cds', 'toys'];

// creating a variable to hold result of orderDetails function with a number array as parameter
const idList = orderDetails(orderid);

// line to populate the result of line no 14


console.log(idList);

// creating a variable to hold result of orderDetails function with a string array as parameter
const nameList = orderDetails(ordername);

// line to populate the result of line no 20


lOMoARcPSD|37346256

console.log(nameList);
Generic Functions
Generic functions are functions declared with generic types.

Declaring generic function is done using the type parameter and using the same type variable for the parameter and the
return type.

Tryout : Generic Functions


Problem Statement
Code to declare a Generic function named printData to return the passed parameter then below mentioned code-snippet
would fit into this requirement.

Activity:

Declare a number datatype variable and populate its details on the console.

Create a class named Product with string parameter productName and display the passed parameter details on console with
the help of the above-declared printData Generic function.
Code in TypeScript
// declaring Generic function named printData
function printData<T>( data: T): T {
return data;
}

// variable declaration to access Generic function


const stringData: string = printData<string>('Hello Generics');

// line to populate the result of Generic function on console.


console.log('String data ' + stringData);
Generic Interface
Generic interface is an interface that works with multiple types

This interface can be implemented by different classes with their own types.
lOMoARcPSD|37346256

Tryout : Generic Interface


Problem Statement
Consider that a developer needs to create a Generic Interface named Inventory consisting of two methods namely addItem
and getProductList and create an object of a class Gadget which implements Inventory interface of string type and to access
these methods then below mentioned code-snippet would works fine.

Activity:

Create an object of a class named Shipping which should implement Inventory interface of number data type as well as the
appropriate logic for both the methods addItem and getProductList methods in order to display the new details on console.

Code in TypeScript
// declaring Generic interface named Inventory
interface Inventory<T> {
addItem: (newItem: T) => void;
getProductList: () => Array<T>;
}

// declaring Gadget class implementing Generic interface Inventory of string type


class Gadget implements Inventory<string> {

// assigning string array value to variable


productList: Array<string> = ['Mobile', 'Tablet', 'Ipod'];

addItem(newItem: string): void {


console.log('Item added');
}

// method to populate the product list


getProductList(): Array<string> {
return this.productList;
}

// creating the reference variable of string type Inventory interface holding Gadget class object
const productInventory: Inventory<string> = new Gadget();

// logic to store the product list information into a variable


const allProducts: Array<string> = productInventory.getProductList();

// line to populate the products details on console


console.log('The available products are : ' + allProducts);
Generic Class
Generic class is a class that works with multiple types.

*
Consider the generic class given below:
lOMoARcPSD|37346256

The same class instance can be instantiated and invoked with different type parameters.

Tryout : Generic Class


Problem Statement
Consider that a developer needs to create a Generic Class named Gadget consisting of two methods addItems and
getProductList to add the list and return the list details respectively then below-mentioned code would work fine with String
data type.

Activity:

Implement a similar logic to populate the details of the number array datatype on the console.
Code in TypeScript
// declaring a Generic Class Gadget
class Gadget <T> {

productList: Array<T>;
addItems(newItemList: Array<T>): void {
this.productList = newItemList;
console.log('Item added');
}

getProductList(): Array<T> {
return this.productList;
}

// Creation of reference variable of Gadget class with String array parameter


const product = new Gadget<string> ();

// Creation of reference variable of String array type


const productList: Array<string> = ['Mobile', 'Tablet', 'Ipod'];

// logic to add product list value to product object


product.addItems(productList);

// Creation of reference variable of String array to hold the return value of getProductList method
const allProducts: Array<string> = product.getProductList();

// line to populate the details of above declared reference variable.


console.log('The available products are ' + allProducts);
Generic Constraints
Generic constraints are used to add constraints to the generic type.

Generic constraints are added using the 'extends' keyword.

Consider the below code:

Here you are trying to access the length property of the function type parameter.

Since the parameter type will get resolved only at run time, this line will throw compilation

To resolve this, you can add a constraint with the type parameter.
lOMoARcPSD|37346256

If you need to access a property on the type parameter, add those properties in an interface or class and extend the type
parameter from the declared interface or class.

Let us rewrite the previous code:

To invoke this generic function, you can pass any parameter which has a length property

Tryout : Generic Constraints


Problem Statement
Consider that a developer needs to declare

An Interface AddLength with length number datatype

A Method named orderLength with Constraints to Generic type and return the length value of invoking variable.

A Class named Product that implements Addlength interface.

Create an object of Product class and invoke the orderLength function this code would work fine.

Activity:

Implement a similar implementation for an array of string datatype and display its length on screen.
Code in TypeScript
// declaring AddLength interface
interface AddLength {
length: number;
}

// declaring orderLength method with Generic constraints


function orderLength<T extends AddLength>(arg: T): T {
const lengthValue = arg.length;
console.log('Length is ' + lengthValue);
return arg;
}

// declaring a class Product implementing AddLength interface


class Product implements AddLength {
length = 10;
}

// variable of Product class


const product: Product = new Product();

// creation of variable which holds the return value of orderLength method


const product1 = orderLength(product);

// line to populate the length of Product class on console


console.log('Product Length ' + product1.length);
lOMoARcPSD|37346256

Exercise : Generics
Problem Statement:

Create a generic function to sort numbers as well as string values.

Refer to the sample output for the same:

Input - 1:

[1,4,2,9,3]

Output - 1:

[1,2,3,4,9]

Input - 2:

[“A”,”K”,”B”,”L”]

Output - 2:

[“A”,”B”,”K”,”L”]
Decorator
Why Decorator?
 Decorator is used for providing metadata and they are used to specify extra behavior of a class, method, or
property of a class.
 Decorators are used for declarative programming.
 Decorators are used for implementing cross-cutting concerns.
 Angular2 makes use of decorators.
 @component, @inject, @service, @pipe are some of the built-in decorators used in Angular2 to apply metadata on
classes to implement different concepts of Angular2.
What is a Decorator?
A decorator is a kind of declaration that can modify or provide metadata for a property, method, or method parameter as well
as for classes.

Decorators use @expression form, where expression can represent a business logic which would be called at runtime with
needed information respectively.

The developer needs to enable decorator through experimentalDecorators compiler option, either of two below mentioned
ways can be used for the same:

through the command line interface

tsconfig.json

Class Decorator
A Class Decorator is used just before a class declaration.-

It can be used to modify, observe, or replace any class definition.

The class decorator can be applied to constructor of user defined class.

The class decorator at runtime overrides the original constructor logic with a new one, returns the only argument.

You can log, modify, or replace the original constructor within the class decorator function.
lOMoARcPSD|37346256

Demo : Class Decorator


Highlights:
 Creating a Class Decorator
 Invoking a Class Decorator
Demo steps:
Step 1: Create a file class_decorator.ts

1. function invoke(constructor:Function) {
1. // the new constructor behaviour
2. const newconstructor: any = function(...args) {
3. this.productId = 875;
4. this.productName = 'Tablet';
5. };
6. // return newconstructor will override the original constructor
7. return newconstructor;
8. }
9. @invoke
10. class Product {
11. public productId: number;
12. public productName: string;
13. constructor(productId: number, productName: string) {
14. this.productId = productId;
15. this.productName = productName;
16. }
17. }
18. const p = new Product(326, 'Mobile');
19. console.log(`Product id is: ${p.productId}`);
20. console.log(`Product name is : ${p.productName}`);

Step 2: Open a command prompt and navigate to the folder in which ts files resides and run tsc
class_decorator.ts command

Step 3: Run node class_decorator.js from the command line

Method Decorator
A Method Decorator are declared before needed method declaration.
 They are used to modify, observe, or replace a method definition.
 The decorator logic is applied to the Property Descriptor attribute of the respective method.
The method decorator function will be invoked at runtime with the below three arguments:
lOMoARcPSD|37346256

 target - Either the constructor function of the class for a static member or the prototype of the class for an instance
member
 Key - name of the decorated method
 descriptor - Property Descriptor value of the method

Demo : Method Decorator


Highlights:
 Creating Method Decorator
 Accessing Method Decorator
Demo steps:
Step 1: Create a file method_decorator.ts

1. function logMethod() {
1. return (target, propertyKey: string, descriptor: PropertyDescriptor) => {
2. return {
3. value: ( ... args: any[]) => {
4. console.log('Arguments: ', args.join(', '));
5. const result = descriptor.value.apply(target, args);
6. console.log('Total Payable Amount is: ', result);
7. return result;
8. }
9. };
10. };
11. }
12. class Product {
13.
14. @logMethod()
15. calculateAmountPayable(price: number, quantity: number) {
16. return price * quantity;
17. }
18. }
19. const p: Product = new Product();
20. p.calculateAmountPayable(220, 3);

Step 2: Open a command prompt and navigate to the folder in which ts files resides and run tsc
method_decorator.ts command

Step 3: Run node method_decorator.js from the command line

Exercise : Decorator
Problem Statement:
1. Create a class Person with a constructor and initialize member variables, name, and surname. Create an instance of the
Person class and log the value of the name and surname variables to the console.
lOMoARcPSD|37346256

Create and apply logClass class decorator to the Person class, which modifies the values of the member variables of the class
Person.
2. Create a method decorator named get and attach it to a function getProductPrice(productId) where return the productPrice
based on the productId.
Within the get method decorator, access the function getProductPrice, and log the productPrice.
Project Configuration- Introduction
Project configuration in TypeScript is used to set the compiler options and helps in specifying the files to be included or
excluded while performing the compilation.
TypeScript project configuration can be done using one of the below approaches:
 tsc: With command line along with the tsc command
 IDE: Setting options using the IDE with which you have coded TypeScript
 Build Tool: Using any task builder like Grunt or Gulp
 tsconfig.json: Inside a file with the name tsconfig.json
Specifying Compiler Option
Compiler option is used to specify configurations like target ES version to be used to compile, module loader to be used, and
so on.
There are many compiler options available which you can refer to from the TypeScript documentation.
Common compiler options used are:

Specifying Compiler Option

Option Description Example

tsc --target ES2015


--target A developer can specify ECMAScript target version:'es3'(default),'es5', or 'es6'
filename.ts

A developer can specify module code generation: 'none','commonjs', 'amd', 'system', tsc --module commonjs
--module
'umd', 'es6', or 'es2015' filename.ts

tsc --outDir foldername


--outDir A developer can redirect output structure to the directory
filename.ts

Helps in concatenation, and emits the output to a single file. Order of concatenation is
tsc --outFile foldername
--outFile determined by the list of files passed to the compiler on the command line along with
filename.ts
triple-slash references and imports

-- tsc --sourceMap
Generates corresponding '.map'file which is used to perform debugging.
sourceMap filename.ts

Run the compiler in watch mode. Watch input files and trigger recompilation on
--watch tsc --watch filename.ts
changes.
Role and Structure of tsconfig.json
 It is used to provide compiler options to a TypeScript project
 It helps in specifying the files to be included or excluded from the project
You can also find the root of a TypeScript application using the tsconfig.json file as this file resides in the root folder.

Once you add tsconfig.json file, you can use the tsc command to compile the files using the tsconfig.json file.
lOMoARcPSD|37346256

Highlights:
 Configuring compiler options in tsconfig.json file
 Using tsconfig.json file to compile
Demo steps:
Step 1: Create a file Namespace_demo.ts

1. namespace Utility {
1. export namespace Payment {
2. export function CalculateAmount(price: number, quantity: number): number {
3. return price * quantity;
4. }
5. }
6. export function MaxDiscountAllowed(noOfProduct: number): number {
7. if (noOfProduct > 5) {
8. return 40;
9. } else {
10. return 10;
11. }
12. }
13. function privateFunc(): void {
14. console.log('This is private...');
15. }
16. }

Step 2: Create another file Namespace_import.ts:

1. /// <reference path="./ Namespace_demo.ts " />


1.
2. import util = Utility.Payment;
3. const paymentAmount = util.CalculateAmount(1255, 6);
4. console.log(`Amount to be paid: ${paymentAmount}`);
5. const discount = Utility.MaxDiscountAllowed(6);
6. console.log(`Maximum discount allowed is: ${discount}`);

Step 3:Create another file tsconfig.json with in the same folder in which the namespace code resides

1. {
1. "compilerOptions": {
2. "target": "es5",
3. "outDir": "Outfile",
4. "sourceMap": true,
5. "watch":true
6. },
7. "files": [
8. "Namespace_demo.ts",
9. "Namespace_import.ts"
10. ]
lOMoARcPSD|37346256

11. }

Step 4: Open Node.js command prompt, change directory to the folder in which ts files resides and run tsc command from
the command line:

You might also like