MSD Unit4
MSD Unit4
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. 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:
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
1. class Product{
1. protected productId:number;
2. }
3. class Gadget extends Product{
4. getProduct():void{
5. }
6. }
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
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.
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.
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
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
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
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.
Output:
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.
The let declared variable cannot be redeclared within the same block.
The var declared variable can be redeclared within the same block.
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
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">
<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> $<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.
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.
Tryout : Enum
Problem Statement
// declaring enum variable and assigning default values
enum MobilePrice {Black= 250, Gold= 280, White= 300}
// 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:
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">
<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
</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;">$</span><span id="gold" style="padding-left: 2px;"></span>
<span style="padding-left: 90px;">$</span><span id="pinkgold" style="padding-left: 2px;"></span>
<span style="padding-left: 65px;">$</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(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:
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">
<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> $<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>
</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 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:
let productName;
let availability;
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.
TypeScript JavaScript
// declaring a function which accepts string datatype as parameter and returns string array
function getMobileByManufacturer(manufacturer: string): string[] {
In a shopping cart application, you can use the arrow function to perform filtering, sorting, searching operations, and so on
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.
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.
Activity:
Modify the function declaration line no 2 as below and re-execute the code.
function getMobileByManufacturer(manufacturer,id?:number): string[]
if (id) {
if (id === 101) {
mobileList = ['Moto G Play, 4th Gen', 'Moto Z Play with Style Mod'];
return mobileList;
}
}
Rest parameter should be the last parameter in the function parameter list.
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> $ <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> $<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> $<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
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.
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> $<span id="pPrice"></span></div>
<div><b>Status:</b> <span id="pAvailable"></span></div>
<div><b class="text-danger">Discount:</b> <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;">$</span><span id="gold" style="padding-left: 2px;"></span>
<span style="padding-left: 90px;">$</span><span id="pinkgold"
style="padding-left: 2px;"></span>
<span style="padding-left: 65px;">$</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?
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.
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 ;
}
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
Activity:
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;
}
Let us rewrite the duck typing example with the optional property.
lOMoARcPSD|37346256
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;
}
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.
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
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 {
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.
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>;
}
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.
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
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
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
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
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.
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.
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();
// 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:
Demo : Accessors
Highlights:
Creating accessors in a class
Accessing accessors
Demo steps:
Step 1: Create a file class_accessors.ts
Step 2: Open a command prompt and navigate to the folder in which interface.ts file resides and run tsc class_accessors.ts
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:
getProduct(): void {
console.log('Product id is : ' + this.productId);
}}
Activity:
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
getFeatures(): string {
return 'This product has camera feature';
}
}
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
Attach the transpiled TypeScript file to the HTML page as highlighted in the above code.
Modules and Namespaces are useful in grouping functionalities under a common name.
Namespaces are used for namespace resolution and are suitable for the development of a smaller application.
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.
The function or any construct which is not exported cannot be accessible outside the namespace.
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
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:
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> $<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> $<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> $<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.
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.
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
10. }
11. }
12. interface Category {
13. getCategory(productId: number): string;
14. }
15. export const productName = 'Mobile';
16. export {Utility, Category};
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
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
Step 3: Open Node.js command prompt, change directory to the folder in which module files resides and run the below
command:
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 the click event handler function, get the productId, productName, and productPrice properties of the current object stored
in the localStorage.
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> $<span id="pPrice"></span></div>
55. <div><b>Status:</b> <span id="pAvailable"></span></div>
56. <div><b class="text-danger">Discount:</b> <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
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
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.
productName: string
quantity: number
price: number
totalPrice: boolean
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.
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
}
.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
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.
// creating a variable to hold result of orderDetails function with a number array as parameter
const idList = orderDetails(orderid);
// creating a variable to hold result of orderDetails function with a string array as parameter
const nameList = orderDetails(ordername);
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.
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;
}
This interface can be implemented by different classes with their own types.
lOMoARcPSD|37346256
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>;
}
// creating the reference variable of string type Inventory interface holding Gadget class object
const productInventory: Inventory<string> = new Gadget();
*
Consider the generic class given below:
lOMoARcPSD|37346256
The same class instance can be instantiated and invoked with different type parameters.
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 String array to hold the return value of getProductList method
const allProducts: Array<string> = product.getProductList();
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.
To invoke this generic function, you can pass any parameter which has a length property
A Method named orderLength with Constraints to Generic type and return the length value of invoking variable.
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;
}
Exercise : Generics
Problem Statement:
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:
tsconfig.json
Class Decorator
A Class Decorator is used just before a class declaration.-
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
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
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
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
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:
A developer can specify module code generation: 'none','commonjs', 'amd', 'system', tsc --module commonjs
--module
'umd', 'es6', or 'es2015' 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 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: