Expt No:
Page No :
Date:
Week 10
10 a) Course Name: Typescript
Module Name: Rest Parameter
Implement business logic for adding multiple Product values into a cart variable which is type of string
array.
Aim: Implement business logic for adding multiple Product values into a cart variable which is type of
string array.
Description:
TypeScript - Rest Parameters
In the function chapter, you learned about functions and their parameters. TypeScript introduced rest
parameters to accommodate n number of parameters easily. When the number of parameters that a
function will receive is not known or can vary, we can use rest parameters. In JavaScript, this is achieved
with the "arguments" variable. However, with TypeScript, we can use the rest parameter denoted by
ellipsis ....
We can pass zero or more arguments to the rest parameter. The compiler will create an array of arguments
with the rest parameter name provided by us.
Program:
const cart: string[] = [];
const pushtoCart = (item: string) => { cart.push(item); }; function addtoCart(...productName: string[]):
string[] {
for (const item of productName) {
pushtoCart(item);
}
return cart;
}
console.log('Cart Items are:' + addtoCart(' Moto G Play, 4th Gen', ' Apple iPhone 5s'));
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
10 b) Course Name: Typescript
Module Name: Creating an Interface
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.
Aim: Declare an interface named - Product with two properties like productId and productName with a
number and string data type and need to implement logic to populate the Product details.
Description: An interface is a syntactical contract that an entity should conform to. In other words, an
interface defines the syntax that any entity must adhere to. Interfaces define properties, methods, and
events, which are the members of the interface. Interfaces contain only the declaration of the members. It
is the responsibility of the deriving class to define the members. It often helps in providing a standard
structure that the deriving classes would follow.
Program:
interface Product { productId: number; productName: string; }
function getProductDetails(productobj: Product): string {
return 'The product name is : ' + productobj.productName;
}
const prodObject = { productId: 1001, productName: 'Mobile' };
const productDetails: string = getProductDetails(prodObject);
console.log(productDetails);
Output:
10 c) Course Name: Typescript
Module Name: Duck Typing
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.
Aim: 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.
Description: Duck-Typing
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
Duck-Typing is a method/rule used by TypeScript to check type compatibility for more complex variable
types. This method is used to compare two objects by determining whether they have the same type of
matching names or not. It means we can't change a variable's signature.
The duck-typing technique in TypeScript is used to compare two objects by determining if they have the
same type matching properties and objects members or not. For example, if we assign an object with two
properties and a method and the second object is only assigned with two properties. The typescript
compiler raises a compile-time error in such situations when we create a variable of object1 and assign it a
variable of the second object type.
Program:
interface Product { productId: number; productName: string; }
function getProductDetails(productobj: Product): string {
return 'The product name is : ' + productobj.productName;
}
const prodObject = { productId: 1001, productName: 'Mobile', productCategory: 'Gadget' };
const productDetails: string = getProductDetails(prodObject); console.log(productDetails);
Output:
10 d) Course Name: Typescript
Module Name: Function Types
Declare an interface with function type and access its value.
Aim :Declare an interface with function type and access its value.
Description: A function type has two parts: parameters and return type. When declaring a function type,
you need to specify both parts with the following syntax:
(parameter: type, parameter:type,...) => type
Code language: PHP (php)
The following example shows how to declare a variable which has a function type that accepts two
numbers and returns a number:
let add: (x: number, y: number) => number;
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
Code language: JavaScript (javascript)
In this example:
The function type accepts two arguments: x and y with the type number.
The type of the return value is number that follows the fat arrow (=>) appeared between parameters and
return type.
Program:
function CreateCustomerID(name: string, id: number): string {
return 'The customer id is ' + name + ' ' + id;
}
interface StringGenerator { (chars: string, nums: number): string; }
let idGenerator: StringGenerator; idGenerator = CreateCustomerID;
const customerId: string = idGenerator('Mr.Tom', 101); console.log(customerId);
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
Experiment-11:
11 a) Course Name: Typescript
Module Name: Extending Interfaces
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.
Aim:To declare a productList interface which extends properties from two other declared interfaces like
Category.
Description: 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.
Example: interface Category{ categoryName:string; }
interface Product{ productName:string; productid:number; }
interface productList extends Category,Product{ list:[‘Samsung’,’Motorola’,’LG’ ] }
Program:
interface Category {
categoryName: string;
}
interface Product {
productName: string;
productId: number;
}
interface ProductList extends Category, Product {
list: Array;
}
const productDetails: ProductList = {
categoryName: 'Gadget', productName: 'Mobile',
productId: 1234, list: ['Samsung', 'Motorola', 'LG']
};
const listProduct = productDetails.list;
const pname: string = productDetails.productName;
console.log('Product Name is ' + pname);
console.log('Product List is ' + listProduct);
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
11 b) Course Name: Typescript
Module Name: Classes
Consider the Mobile Cart application, Create objects of the Product class and place them into the
productlist array.
Aim: To consider the Mobile Cart application, Create objects of the Product class and place them into the
productlist array.
Description: TypeScript is object oriented JavaScript. TypeScript supports object-oriented
programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating
objects. A class encapsulates data for the object. Typescript gives built in support for this concept called
class. JavaScript ES5 or earlier didn’t support classes. Typescript gets this feature from ES6. Use the class
keyword to declare a class in TypeScript.
Program:
class Product {
static productPrice: string;
productId: number;
constructor() {
this.productId = 1234;
}
getProductId(): string {
return 'Product id is : ' + this.productId;
}
}
const product: Product = new Product();
const p = {
producti: product.getProductId(),
};
console.log(p.producti);
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
11 c) Course Name: Typescript
Module Name: Constructor
Declare a class named - Product with the below-mentioned declarations: (i) productId as number property
(ii) Constructor to initialize this value (iii) getProductId method to return the message "Product id is <<id
value>>".
Aim: To declare a class named - Product with the below-mentioned declarations:
(i)productId as number property (ii) Constructor to initialize this value (iii) getProductId method to return
the message "Product id is <>" .
Description: A constructor is a special function of the class that is automatically invoked when we
create an instance of the class in Typescript. We use it to initialize the properties of the current instance of
the class. Using the constructor parameter properties or Parameter shorthand syntax, we can add new
properties to the class. We can also create multiple constructors using the technique of constructor method
overload. The constructor method in a class must have the name constructor. A class can have only one
implementation of the constructor method. The constructor method is invoked every time we create an
instance from the class using the new operator. It always returns the newly created object.
Program:
class Product {
static productPrice: string;
productId: number;
constructor(productId: number) {
this.productId = productId;
}
getProductId(): string {
return 'Product id is : ' + this.productId;
}
}
const product: Product = new Product(1234);
console.log(product.getProductId());
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
11 d) Course Name: Typescript
Module Name: Access Modifiers
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.
Aim: 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.
Description: Like other programming languages, Typescript allows us to use access modifiers at the
class level. It gives direct access control to the class member. These class members are functions and
properties. We can use class members inside its own class, anywhere outside the class, or within its child
or derived class.The access modifier increases the security of the class members and prevents them from
invalid use. We can also use it to control the visibility of data members of a class. If the class does not
have to be set any access modifier, TypeScript automatically sets public access modifier to all class
members.
Program:
class Product {
static productPrice = 150;
private productId: number;
public productName: string;
protected productCategory: string;
constructor(productId: number, productName: string, productCategory: string) {
this.productId = productId;
this.productName = productName;
this.productCategory = productCategory;
}
getProductId() {
console.log('The Product id is : ' + this.productId);
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
}
}
class Gadget extends Product {
getProduct(): void {
console.log('Product category is : ' + this.productCategory);
}
}
const g: Gadget = new Gadget(1234, 'Mobile', 'SmartPhone');
g.getProduct();
g.getProductId();
console.log('Product name is : ' + g.productName);
console.log('Product price is : $' + Product.productPrice);
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
Experiment-12:
12 a) Course Name: Typescript
Module Name: Properties and Methods
Create a Product class with 4 properties namely productId and methods to setProductId() and
getProductId().
Aim: To create a Product class with 4 properties namely productId and methods to setProductId() and
getProductId().
DESCRIPTION: In typescript, the method is a piece of code that has been declared within the class and it
can be carried out when it is called. Method property in it can split a huge task into little sections and then
execute the particular operation of that program so that code can be reusable which can improve the
module from the program.
Program:
// declaring a Product class
class Product {
static productPrice: string;
productId: number;
constructor(productId: number) {
this.productId = productId;
}
getProductId(): string {
return 'Product id is : ' + this.productId;
}
}
const product: Product = new Product(2345);
console.log(product.getProductId());
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
12 b) Course Name: Typescript
Module Name: Creating and using Namespaces
Create a namespace called ProductUtility and place the Product class definition in it. Import the Product
class inside productlist file and use it.
AIM: To create a namespace called ProductUtility and place the Product class definition in it. Import the
Product class inside productlist file and use it.
DESCRIPTION: In typescript, the method is a piece of code that has been declared within the class and it
can be carried out when it is called. Method property in it can split a huge task into little sections and then
execute the particular operation of that program so that code can be reusable which can improve the
module from the program. The classes or interfaces which should be accessed outside the namespace
should be marked with keyword export. To access the class or interface in another namespace, the syntax
will be
namespaceName.className
Program:
namespace_one12b.ts:
import util = Utility.Payment;
let paymentAmount = util.CalculateAmount(1800, 6);
console.log(`Amount to be paid: ${paymentAmount}`);
namespace_two12b.ts:
namespace Utility {
export namespace Payment {
export function CalculateAmount(price: number, quantity: number): number {
return price * quantity;
}
}
}
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
12 c) Course Name: Typescript
Module Name: Creating and using Modules
Consider the Mobile Cart application which is designed as part of the functions in a module to calculate
the total price of the product using the quantity and price values and assign it to a totalPrice variable.
Aim: To creating and using Modules Consider the Mobile Cart application.
DESCRIPTION: A module refers to a set of standardized parts or independent units that can be used to
construct a more complex structure. TypeScript modules provides a way to organize the code for better
reuse.
Program:
module_one12c.ts:
export function MaxDiscountAllowed(noOfProduct: number): number {
if (noOfProduct > 5) { return 30; }
else { return 10; }
}
class Utility {
CalculateAmount(price: number, quantity: number): number {
return price * quantity;
}
}
interface Category { getCategory(productId: number): string; }
export const productName = 'Mobile';
export { Utility, Category };
module_two12c.ts:
import {Utility as mainUtility, Category, productName, MaxDiscountAllowed } from "./module_one12c";
const util = new mainUtility();
const price = util.CalculateAmount(1350, 4);
const discount = MaxDiscountAllowed(2);
console.log(`Maximum discount allowed is: ${discount}`);
console.log(`Amount to be paid: ${price}`);
console.log(`ProductName is: ${productName}`);
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM
Expt No:
Page No :
Date:
12 d) Course Name: Typescript
Module Name: What is Generics, What are Type Parameters, Generic Functions, Generic
Constraints
Create a generic array and function to sort numbers as well as string values.
Aim: To create a generic array and function to sort numbers as well as string values.
Description: Whenever any program or code is written or executed, one major thing one always takes
care of which is nothing but making reusable components which further ensures the scalability and
flexibility of the program or the code for a long time. Generics, thus here comes into the picture as it
provides a user to flexibly write the code of any particular data type (or return type) and that the time of
calling that user could pass on the data type or the return type specifically. Generics provides a way to
make the components work with any of the data types (or return types) at the time of calling it for a
certain number of parameters (or arguments). In generics, we pass a parameter called type parameter
which is put in between the lesser sign (<),and the greater sign (>) for example, it should be like
<type_parameter_name>.
Program:
// declaring a Generic Array named orderDetails
function orderDetails<T>(arg: Array<T>): Array<T> {
console.log(arg.length);
return arg;
}
const orderid: Array = [201, 202, 203, 204];
const ordername: Array = ['Dresses', 'Toys', 'Footwear', 'cds'];
const idList = orderDetails(orderid);
console.log(idList);
const nameList = orderDetails(ordername);
console.log(nameList);
Output:
ADITYA ENGINEERING COLLEGE , SURAMPALEM