Wednesday, 12 February 2020

Typescript


Typescript

(1) With the help of HTML we can create webpages.
(2) With the help of CSS and Bootstrap we can provide style and responsive nature and it is also possible to give dynamic or interactive nature of a webpage.
(3) With the help of JavaScript.
à There are some limitations in JS like not fully supporting of classes, interfaces and in JS data types are dynamic means whenever we assign value or data, then its type is specified and it is also possible to pass another data type to a variable that will give abnormal results, and take some time to pass the result.
à In order to overcome this kind of limitations we have a special kind of programing language called Typescript.
Typescript
It is a superset of JavaScript it means it is next level of JS, all JS functions, keywords are supported by Typescript.
à Typescript is developed by Microsoft Corporation.
à Typescript helps developers to do programs in object oriented methodology, and it also make simple programmer can work on both front end and back end technologies.
à By this so many frameworks are existed to increase the development speed.

Installation of Typescript: -
In order to work on Typescript we have to install some kind of software’s in our local machine.
Step (1):- Node Installation
(1) In order to use Typescript we need node JS platform, in order to provide node JS platform we have to install node JS in our local system/machine.
(2) We need to visit https://nodejs.org/en/ official website there we can found node JS software for different platforms/OS and download those software and install in local machines.
(3) With the help of below command is possible to check whether the machine contain node or not.
node –v
or
node --version
(4) When we try to install node node package manager (npm) is automatically install along with node JS.
(5) The help of npm we can install any kind of libraries, modules, tools easily.
(6) In order to check the npm version below commands are helpful
npm –v         
or
npm --version

Step (2):- Install in Typescript
npm install –g typescript
à The help of above command we can install Typescript in our local machines to by specifying/ asking npm to install Typescript globally (-g).
à The help of below command we can check Typescript weather install or not.
tsc
or
tsc --version

Typescript dealing with browsers: -
In generally browsers only understand JavaScript because of JS Engines every browser internally contain JS Engine browsers did it understand Typescript directly. So, we need to convert/ transpiration to do this we use tsc (typescript compiler).

Run
        a.ts                       tsc a.ts                                        Node a.js
a.js File
Compiler
Output
Code/
Source file
 

Working with TS files/programs:-
Step 1:- Save the source code file with .ts extension then compiler will know it’s a typescript file.
Step 2:- Converting .ts to .js file
In order to do this we need console (terminal)/ command prompt. In visual code there is an option to open terminal like in menu bar there is a view tab dropdown click it contain terminal option.
In latest visual code menu bar itself contain Terminal option we can click on that open new terminal.
Step 3:- Using transpiler with the help of below command we convert TS file to JS file.
tsc filename.ts

The above command generate JS file with the name as TS filename.
Step 4:- Executing/Running of JS file we can run JS file in browser as well as node.
In this section we focus on mainly how to run JS file in node platform.
The below command is helpful to run
node filename.js

Example:-
a.ts
var a=10;
var b=20;
console.log(a+b);
a.js
var a=10;
var b=20;
console.log(a+b);

(1) Click Terminal buttonà type tsc filename.ts ànode filename.js à showing Output
(2) In the above example there is no difference in source code of ts file and js file.
(3) In the above code there is no type safety. To provide type safety ts have data types which are explicitly specify types.

Data types in Typescript:-
Basic data types which are supported by
number- to specify all types of numbers.
string- to specify group of chars.
boolean- to specify true or false.
any- to specify store any kind of data.
number[]- to specify number array.
string[]- to specify string array.
null,
undefined.
Defining variables in Typescript:-

Variable_name:data_type; àvalue undefined
Var a:number; //a=10;
Var b:string; //b=”20”;
Var c:number[]; //c=[1,2,3,4];
Var d:Boolean; //d=true;

Class: - Class is a logical design of physical existence entities. Logical existence means it did it occupy space in RAM.
Syntax: -
class class_name{
//Datamembers / State
//Methods / Actions
}

(1) We use “class” keyword to define a class like above syntax. Every class has contain name and body, body contain data members and methods.
(2) Data members are used to represent state and methods are used to represent actions.

Define Data Members in class: -
variable_name: data type; //Ex: - a.number;
We did it use var/let keyword to define a variable in side class, why because those are instance variables means those data members are belongs to class only.

Define Methods in class: -
Methods are used to represent to perform business logic.
Syntax: -
method_name:return type{
//Statements
}

Example: -
class Greetings
{
    say_hi:string="Anil";
    sayGreeting():void{
        console.log(this.say_hi);
    }
}
Creating Object: - If we run above code won’t display anything, why because we define class, class is logical existence only. In order to bring this logical existence to physical existence we have to create object for this class.
Syntax: -
Object_name=new class_name();

Example: -
var obj=new Greetings();

Invoking (calling) methods through object: -
Syntax: -
Object_name.method_name();

Example: -
obj.sayGreeting();

(1) In the above example we used “class” keyword to define class.
(2) We used “Void” keyword to specify return type of method.
(3) We used “this” keyword for current object.
(4) We used “new keyword for current object.
(5) We used “var” keyword to define variable object that holds object of class.

Constructors
It is a special kind of method which is used to initialize the object.
There are 2 types of constructors
(1) Default constructor: - It is used to initialize the object/ to create an instance of a class.
Example: -

class A
{
    constructor(){

                    }
    }
var obj=new A(); 
(2) Parameterized constructor: - It is used to initialize the instance variable.

Example: -

class stu
{
    a:number; //instance variable
    constructor(b:number)  //Local instance variable/parameters
    {
        this.a=b;
    }
    print():void{
        console.log(this.a);
    }
}
var obje=new stu(20);  //A() argument
obje.print();

Example-1.ts: -

class Student
{
    name:string;
    age:number;
    id:number;
    constructor(name:string,age:number,id:number)
    {
        this.name=name;
        this.age=age;
        this.id=id;
    }
    details(): void{
        console.log(`Name:${this.name}\nAge:${this.age}\nId:${this.id}`);
    }                                                                                                           
}
var objec1=new Student("Anil",25,12);
objec1.details();
var objec2=new Student("sree",24,11);
objec2.details();

Example-2.ts: -

class Students
{
student:object[]=
[
    {name:"Anil", age:28, id:11, Marks:[1,2,3,4]},
    {name:"sree", age:27, id:12, Marks:[1,2,4,5]},
    {name:"Ajay", age:26, id:13, Marks:[1,2,5,7]},
    {name:"Swech", age:25, id:14, Marks:[1,2,8,5]},
    {name:"Get", age:24, id:15, Marks:[1,2,7,9]}
];
findAvg():void{
    let student=this.student.map(x=>{
        x['Marks']=x['Marks'].map (y=>{
            return y+10;
        });
        return x;
    });
    this.student.forEach(x=>{
        let TotalMarks=x['Marks'].reduce((a,b)=>{
            return a+b;
        });
        x['Avg']=TotalMarks/x['Marks'].length;
    });
    this.student.sort((x,y)=>{
      return x['id']-y['id'] //Asending order
        return y['id']-x['id']
        //return x['Avg']-y['Avg']  //Asending order
        //return y['Avg']-x['Avg'] //desending order
    })
    console.log(this.student)
    this.student=this.student.filter(x=>{
        return x['Avg']>13;
    })
    console.log(this.student)
}
}
var objec=new Students();
objec.findAvg();

(1) In above example-2.ts we used “map” function it is a call back function means a function has another function as parameter.
(2) We used “arrow (==>)” function to define/create function (anonymous function (without name)).
(3) Map function return new array depending on business logic given in arrow function, and it iterate each element and return each element.
(4) We used “forEach” function to iterate array. It is also call back function, but it did it return anything. (We used this for iteration purpose)
(5) We use “reduce” function it is call back function means a function has another function as parameter. Generally it returns result based on business logic. It iterates all elements but return single result.
(6) We used “sort” function for sorting for an array ascending/descending depending on business logic.
(7) We used “filter” function this is return new array depending on business logic it iterates all elements but return only elements which are satisfy business logic.
var a=10;
console.log(`$(a) is a number\n and is even`); //typescript
console.log(a+ is a number\n and is even); //JavaScript
In generally to console values with statements we use + operator.
In Typescript we use ``side quotations with $ symbol and {} curly braces like below one.
console.log(`Name:${this.name}\nAge:${this.age}\nId:${this.id}`);

Inheritance
An object acquired all the properties from another object are known as Inheritance.
A sub class (child) acquired all the properties from super (parent) class are known as Inheritance.
Syntax: -
Class parent _class
{
//statements
}
Class child_class extends parent_class
{
//statements
}

If we want to inherit properties from one object to another object they should be in relation.
There are so many relations are there like
(1) IS-A relation (Inheritance)
(2) HAS-A relation (aggregation)
We are mainly focusing on IS-A relation with the help of IS-A relation we can provide extra features to existing object (features) but we can’t do this HAS-A relations.
We can make IS-A relation with 2 keywords
(1) extends
(2) implements
We can use extend keyword between same kind of objects.
Super class_name extends sub class_name;
Super interface_name extends sub Interface_name;

We can take IS-A relation with implement keyword like
Class implements interface
Interface implements class.
Example.ts: -
class Activa3G
{
max_speed:number=100;
color:string="black";
}
class Activa4G extends Activa3G
{
   max_speed:number=120;
    run():void{
        console.log(this.max_speed);
        console.log(this.color);
    }
}
var obj=new Activa4G();
obj.run();

Output:-
120
black

BikeEx.ts: -

class Bike
{
    speed_limit:number=100;
    constructor(speed_limit:number)
    {
        this.speed_limit=speed_limit;
    }
    speedlimit():void
    {
        console.log(this.speed_limit);
    }
}
class Unicorn extends Bike{
    constructor()
    {
        super(100);
    }
}
class Bullet extends Bike{
    constructor()
    {
        super(200);
    }
}
var vehicle=new Bike(100);
var Uni=new Unicorn();
var Bul=new Bullet();
vehicle.speedlimit();
Uni.speedlimit();
Bul.speedlimit();

Output:-
100
100
200

In above example Bike has speed limit that is inherit by all other Bike types and we use “super” keyword to call/invoke super class (parent) constructor.
Polymorphism: - It means an action can perform in many ways.
Poly means many Orphism means ways.
Polymorphism is 2 types
(1) Compile time/Method overloading
(2) Run time/ Method overriding
Method overloading is not supported in Typescript.
Method overriding: - the right method will be decided at run time. By using method overriding is to achieve runtime polymorphism.
Overriding: - The sub class predefined some features of a method existed in superclass. In order to do this the 2 classes have IS-A relation and the method name/signature of a method should be same in both classes.
Example.ts: -

class Grandfath
{
    land:number=100;
    Job(b:string):void
    {
        if(b=="yes")
        {
            this.land +=10;
        }
    }
    property():void{
        console.log(this.land);
    }
}
class father extends Grandfath
{
    Job(b:string):void
    {
        let a=20;
        if(b=="no")
        {
            this.land=this.land-a;
        }
    }
    badhabbits(b:string):void
    {
        if("yes")
        {
            this.land=this.land-20;
        }
    }
    property():void
    {
        console.log(this.land);
    }
}
var Grandf=new Grandfath();
Grandf.Job("yes");
Grandf.property();
var Fath=new father();
Fath.Job("no");
Fath.badhabbits("yess");
Fath.property();

Static binding: - It is nothing but assigning same class object to same class reference.

Example: -

class A
{
}
class B extends A
{
}
var a=new class A();  (or)  //var a: A;  a=new A();
var b=new class B();  (or)  //var b: B;  b=new B();

At compile time that will be decided which method is going too executed.

Dynamic Binding: - It is nothing but assigning child class object to parent class reference, this is also known as dynamic method dispatch. In dynamic binding the executed method will be decided at runtime.
Syntax: -
var b:B;
B=new A();

Example: -

class WhatsApp
{
    features():void{
        console.log("Text chat only");
    }
}
class WhatsApp_v1 extends WhatsApp
{
    features():void{
        console.log("Text chat");
        console.log("Voice call");
        console.log("video calls");
    }
}
class WhatsApp_v2 extends WhatsApp_v1
{
    features():void{
        console.log("Text chat");
        console.log("Voice call");
        console.log("video calls");
        console.log("Group voice call");
        console.log("Group video call");
    }
}
var WhatApp:WhatsApp=new WhatsApp_v2();
WhatApp.features();

HAS-A relation /Aggregation:
It is also one kind of code reusability concept. In this relation, we are making relation through passing one class object to another class object.
In this relation we use 2 classes
(1) Independent class
(2) Depending class
Depending class is depends on independent class object by the object reference concept.
Example: -

class Address
{
House_number:string;
City:string;
State:string;
Pin:number;
constructor(House_number:string,City:string,State:string,Pin:number)
{
    this.House_number=House_number;
    this.City=City;
    this.State=State;
    this.Pin=Pin;
}
}
class CStudent
{
Name:string;
Id:number;
add:Address;
constructor(Name:string,Id:number,add:Address) 
//Note:- add:Address also called as dependency injection.
{
    this.Name=Name;
    this.Id=Id;
    this.add=add;
}
details():void
{
console.log(`Name:${this.Name}\n Id:${this.Id}\n
Address:${this.add.House_number},${this.add.City},${this.add.State},${this.add.Pin}`);
}
}
var add=new Address("D-no-7-71","Hyderabad","TS",523167);
var detect=new CStudent("ANIL",28,add);
detect.details();


class CEmployee
{
    Name:string;
    Id:number;
    Salary:number;
    add:Address;
    constructor(Name:string,Id:number,Salary:number,add:Address)
    {
        this.Name=Name;
        this.Id=Id;
        this.Salary=Salary;
        this.add=add;
    }
    details1():void
{
    console.log(`Name:${this.Name}\n Id:${this.Id}\n Salary:${this.Salary}\n
    Address:${this.add.House_number},${this.add.City},${this.add.State},${this.add.Pin}`);
}
}
var add=new Address("D-no-501","Vijayawada","AP",523216);
var detect1=new CEmployee("Sree",27,30000,add);
detect1.details1();

Abstraction:
Abstraction is a process of hiding the implementation details and showing the only functionalities.
We can implement abstraction in 2 ways
(1) Abstract class
(2) Interfaces
(1) Abstract Class: - It is a class with “abstract keyword. In generally a class contains only concrete methods.
But abstract class contains abstract methods.
Example: -
//Note: We can’t create object for abstract class.

abstract class Netmodems
{
Software():void
{
    console.log("Software is developed by me.");
}
abstract Hardware():void;
    Product()
    {
        this.Software();
        this.Hardware();      
        console.log("Product is ready");
    }
}

class Jio extends Netmodems
{
    Hardware():void
    {
        console.log("Hardware is developed by Jio"); 
    }
}
var Modem:Netmodems=new Jio();
Modem.Product();

Output: -
Software is developed by me.
Hardware is developed by Jio
Product is ready

(2) Interfaces: - It is a blue print for class which contain only abstract methods with the help of “interface” keyword we can define interface and also we can’t create instance for interfaces.
Example: -
interface Bank{
    MinimumBalance():void;
    RateofInterest():void;
    details():void;
}
class SBI implements Bank
{
    MinimumBalance():void{
        console.log("Minimum Balance is 1200/- for SBI");
    }
    RateofInterest():void{
        console.log("Rate of interest is 10% for SBI");
    }
    details():void
    {
        this.MinimumBalance();
        this.RateofInterest();
    }
}
var SBIBank:Bank=new SBI();
SBIBank.details();

Data-modifiers:
With the help of data modifiers we can implement encapsulation. It means wrapping up code and data together.
There are 2 types of data modifiers
(1) Access modifiers
(2) Non-access modifiers

(1) Access modifiers: - It is modify/change the visibility/accessibility of a variable/data member.
(2) Non-access modifiers: - It is didn’t change the visibility/accessibility of variable/data members.
(1) Access modifiers: -
                                    Public
                                    Private
                                    Protected
Public: - In typescript by default all data members have public access that means we can access data from anywhere.
Private: - If we use private keyword before a data member, we are restricting accessibility of that data member. If we want to access the data, we can use setters and getters functions.
We can access private data member with in the class only.
Protected: - If we use protected keyword before a variable. If we can restrict access of the variable but we can access that variable in child class.
class A{
private a:number=100;
public b:number=200;
protected c:number=300;
}
Class B extends A{
print():void
{
console.log(this.a);
console.log(this.b);
console.log(this.c);
}
}
var obje=new B();
obje.print();

In the above example we used private keyword to define private variables (or) to make as A private variable.
à We used B public variable to define B as public data members.
à We used protected keyword to define C as protected data member and we accessing public & protected data members only. When we are trying to call a variable it throwing error, because it is a private member and we can access it only within the class A.

(2) Non-access modifiers: - It is change the behavior of a data member. It we like static/read only.
class A{
public static a:number=100;
public static readonly b:number=200;
}
Class B extends A{
Public static print():void
{
console.log(A.a=500);
console.log(B.b=1000);
}
}
B.print();

In the above example we use static keyword to change the behavior of variable and method.
So with the help of static keyword we can call/access the instance data without creating object and use read only keyword to restrict the variable by varying data.




















Typescript Programs for Assignments

Example-1.ts

class declare
{
a:number=10;
b:number=20;
}
class Sum extends declare
{
    sum():void{
        console.log(this.a+this.b);      
    }
}
var obj1=new Sum();
obj1.sum();

Example-2.ts

class e
{
a:number=10;
}
class f extends e
{
    b:number=20;   
}
class g extends f
{
    sum():void{
        console.log(this.a+this.b);
    }   
}
var obj2=new g();
obj2.sum();

Example-3.ts

class en
{
a:number=10;
b:number=20;
}
class fn extends en
{
    prin():void{
    console.log("value of b is:-"+this.b);
}
}
class gn extends en
{
    priny():void{
        console.log("value of a is:-"+this.a);
    }
}
var obj3=new fn();
obj3.prin();
var obje2=new gn();
obje2.priny();

Example-4.ts

class A
{
    constructor(a)
    {
             console.log("I am from A class",a);
    }
}
class B extends A{
    constructor(a,b)
    {
        super(a);
        console.log(b);
    }  
}
class C extends B{
    constructor(a,b,c)
   {
        super(a,b);
        console.log(c);
    }  
}
var Con=new C(10,20,30);








No comments: