Thursday, September 21, 2023

Inheritance In Typescript Part 8

 Inheritance:

It is one of the key feature of OOPS.

It enables code extensibility and allows loosely coupled architecture.

It is the process of creating a new class that extends existing class.

The newly created class is known as derived class and existing class is known as super class.

typescript is providing "extends" to work with inheritance

Syntax:


class Super

{

    //Super Class Members

}

class Derived extends Super {

//Derived class Members

}

The code can be reused by using Inheritance which is known as Has a Relation

The members of super class are accessible in derived class by using the keyword "this"

Syntax with constructor

syntax:
   class <derv|sub classname>  extends <base|super classname>
   {
     constructor(--)
     {
        super(--); //calling base constructor to initialize base class fields
        initialize derv class fields
     }
     <methodname>(--)
     {
       super.<methodname>(--);
        ...
     }
      ...
   }
class Base
{
    public x:number=10;
}
class Derived extends Base{
    public y:number=20;
    public print():void {
        console.log("x=" + this.x + "\n" + "y=" + this.y);
    }
}
let objderived=new Derived();
objderived.print();

Output:

x=10 y=20


Will typescript supports multiple inheritance for a class
No

Why multiple inheritance is not supported for classes.
Inheritance depends on constructor, when you create a derived class object, first
base class constructor is called than followed by derived. If they are multiple base
classes then there will be conflicts between the constructors. Hence multiple inheritance
is not supported.

MultiLevel Inheritance

It is the process, where in derived class can be extended by new class , so that
it can be access both derived and super class members.

Example

class ProductId {
    public Id:number;
}
class Details extends ProductId
{
    public Name:string;
    public Price:number;
}
class ProductInfo extends Details
{
    public print():void {
        console.log("Id="+ this.Id);
        console.log("Name="+ this.Name);
        console.log("Price="+ this.Price);
    }
}
let objproductInfo=new ProductInfo();
objproductInfo.Id=1;
objproductInfo.Name="Samsung";
objproductInfo.Price=4353;
objproductInfo.print();


Output:

Id=1
Name=Samsung
Price=4353



Example 2

class Department {
    name: string;
   
    constructor(name: string) {
        this.name = name;
    }
}

class  Employee extends Department {
    empCode: number;
   
    constructor(empcode: number, name:string) {
        super(name);
        this.empCode = empcode;
    }
   
    displayName():void {
        console.log("Department Name = " + this.name +  ", Employee Code = " + this.empCode);
    }
}

let emp = new Employee(100, "IT");
emp.displayName();


Output:

Department Name = IT, Employee Code = 100

Note: In the above example
The constructor of the Employee class initializes its own members as well as the parent class's properties using a special keyword 'super'. The super keyword is used to call the parent constructor and passes the property values.


Class implements Interface


interface IPerson {
    name: string;
    display():void;
}

interface IEmployee {
    empId: number;
}

class Employee implements IPerson, IEmployee {
    empId: number;
    name: string;
   
    constructor(empId: number, name:string) {
        this.empId = empId;
        this.name = name;
    }
   
    display(): void {
        console.log("Name = " + this.name +  ", Employee Id = " + this.empId);
    }
}

let per:IPerson = new Employee(100, "Uday");
per.display(); // Name = Bill, Employee Code = 100

let emp:IEmployee = new Employee(100, "Uday");
emp.display(); //Compiler Error: Property 'display' does not exist on type 'IEmployee'



Contracts in OOPS(Typescript Part 7 )

 Contracts in OOPS:


A contract defines a set of rules which are mandatory for any component to implement any specific functionality.
In OOPS, contracts are defined by using interface
An interface specifies rules for any component.
Interface comprises of members which are by default public in access. Hence access specifiers are not required for an member in interface.

Syntax:
interface Name {
    property:type;
}

Interface can be implemented by using a class with "implements" keyword.

Syntax:
class ClassName  implements interfaceName

A member can  implement the contract by using it as a type
Syntax
public property: interfaceName;

Every members defined in contract is not nullable, i.e reference for the member must be defined in implementation.

You can designate the non nullable members into nullable  i.e optional by using a null reference character  ( " ? " )

Example

interface  Iproduct {
    Name:string;
    Price: number;
    Qty? :number;  
}
let products: Iproduct= {
    Name: "TV", Price: 345
}
console.log("Name=" + products.Name);
console.log("Price=" + products.Price);
console.log("Quantity=" + products.Qty);

Output:

Name=TV Price=345 Quantity=undefined PS C:\Examples>


Example 2:

interface  Product {
    Name:string;
    Price: number;
    Qty? :number;  
}
let products: Product[] =[
    { Name: "TV", Price: 345 },
    { Name: "Mobile" , Price : 43 ,Qty:2 }
];
for(var item in products)
{
    console.log(products[item]);
}

Output:
{ Name: 'TV', Price: 345 } { Name: 'Mobile', Price: 43, Qty: 2 }

The interface members are by default virtual. Hence they can be overidden any number of times.
You can restrict the override after initialization by using "read only" 

Example




Difference between read only / const is
const is associated with variables
readonly is associated with properties.

Interface Methods:

The method specifies action for any components
The method are represented with " () "
The method are implemented by the keyword "function"

Syntax

interface Name {
(params) : returnType
}


Example

interface IMethod {
    ():string
}
let myMethod:IMethod;
myMethod=function():string {
    return "Welcome";
}
console.log(myMethod());

Output:

Welcome

Combination of properties and Methods

interface IMethod {
    Id:number;
    Name:string;
    price:number;
    isAvailable:boolean;
    Qty:number;
    Total(Qty:number,price:number):number;
}
let myMethod:IMethod= {
    Id:1,
    Name:"TV",
    price: 4444,
    Qty:2,
    isAvailable:true,
    Total(Qty: number, price : number) {
        return Qty * price
    }
}
console.log(myMethod.Qty);
console.log("Total= "  + myMethod.Total(myMethod.Qty,myMethod.price))

Output

2 Total= 8888

Extending Interface

An interface defined with specified rules can be extended with more functionality by
using "extends" keywords

interface Iversion1
{
    notepad:string;
}
interface Iversion2 extends Iversion1 {
    mspaint:string;
}
let appversion: Iversion2= {
    mspaint:"Text-Paint",
    notepad:"Text-Editor",
}
console.log(appversion.mspaint);
console.log(appversion.notepad);

Output

Text-Paint Text-Editor


Example
interface IBackEffect
{
    bgcolor:string;
    bgimage:string;
}
interface ITextEffects
{
    align:string
    forecolor:string
}
interface IEffects extends IBackEffect,ITextEffects {
    border:number;
}
let effects: IEffects= {
    bgcolor:"red",
    align:"center",
    border:2,
    forecolor:"white",
    bgimage:"shipimage"
}
console.log(effects.bgcolor);
console.log(effects.align);
console.log(effects.border);
console.log(effects.forecolor);

Output

red
center
2
white

interface IEmployee {
    empId: number;
    name: string;
    getSalary:(empCode: number) => number;
}

class Employee implements IEmployee {
    empId: number;
    name: string;

    constructor(Id: number, name: string) {
        this.empId = Id;
        this.name = name;
    }

    getSalary(empCode:number):number {
        return 20000;
    }
}

let emp = new Employee(1, "Uday");

Example of Interface with Arrow Function

interface IEmployee {
    empId: number;
    empName: string;
    getSalary: (number) => number;
    getManagerName(number): string;
}

Interface as Type 
Interface in TypeScript can be used to define a type and also to implement it in the class.

Interface is used as type of variable
interface KeyPair {
    key: number;
    value: string;
}

let kv1: KeyPair = { key:1, value:"Uday" }; // OK

let kv2: KeyPair = { key:1, val:"Kumar" }; // Compiler Error: 'val' doesn't exist in type 'KeyPair'

let kv3: KeyPair = { key:1, value:100 }; // Compiler Error:



Example
interface Idraw
{  area(); }
class circle implements Idraw
{
    constructor(private radius:number) {}
    area() {
      let result=3.14*this.radius*this.radius;
      console.log("area of circle:"+result);    
    }
}
class rect implements Idraw
{
    constructor(private l:number,private b:number) {}
    area() {
        let result=this.l*this.b;
        console.log("area of rect:"+result);
    }
}
let circleobj=new circle(6);
let rectobj=new rect(5,7);
circleobj.area();
rectobj.area();
//polymorphism
console.log("result with polymorphism:")
let draw:Idraw;
draw=new circle(6);
draw.area();
draw=new rect(5,7);
draw.area();
Output



Note:
-----
*interface doesn't allow object creation, but variable can be declared
*interface can reference to an object of a class,which implements an interface
*interface can implement polymorphism
      d=new circle(6);
      d.area();
      d=new rect(6,7);
      d.area()            ==> d.area() is providing more than one form[behavior]
                              is called polymorphism, this consumes less
                              memory resources compare to normal approach







Interview Question Difference between let vs var & const in Type Script (Part 7)

 Advantages of using let over var

We cannot read or write before they are declared , if the variable is declared as let .Whereas it won't give an error when using variables before declaring them using var.

console.log(num1);
let num1:number = 10 ;

console.log(num2);
var num2:number = 10 ;

Output



variables declared with let cannot be re-declared

The TypeScript compiler will give an error when variables with the same name (case sensitive) are declared multiple times in the same block using let.

Whereas it wont give any error when declaring variable with var.

var num:number = 02; // OK
var Num:number = 22;// OK
var NUM:number = 34;// OK
var NuM:number = 444;// OK

let num:number = 52;// Compiler Error: Cannot redeclared block-scoped variable 'num'
let Num:number = 66;// Compiler Error: Cannot redeclared block-scoped variable 'Num'
let NUM:number = 77;// Compiler Error: Cannot redeclared block-scoped variable 'NUM'
let NuM:number = 88;// Compiler Error: Cannot redeclared block-scoped variable 'NuM'
Note:
Variables with the same name and case can be declared in different blocks using let.

const
Variables can be declared using const as well. If declared const it values cannot be changed

const num:number = 100;
num = 200; //Compiler Error: Cannot assign to 'num' because it is a constant or read-only property

Const variables must be declared and initialized in a single statement. Separate declaration and initialization is not supported.

const num:number; //Compiler Error: const declaration must be initialized
num = 100; 

Wednesday, September 20, 2023

Operators in TypeScript Part 6

 What is operator

Operator is an object in computer programming used to evaluate an value based  on the operands defined

The operators are categorized into various groups

1 Arithmetic Operator

2 Comparison Operator

3 Bit-Wise Operator

4 Logical Operator

5 Assignment Operator

6 Special Operator

 

Arithmetic Operator

+ Addition

- Subtraction

* Multiplication

/ Division

% Modules(Reminder)

++ (Increment)

-- ( Decrement)


2  Comparison Operator

== Is Equal to   (10==20)

=== Identical Equal and of same Type  (10===20)

!= Not Equal to

!== Not Identical

> Greater than

< Less than


3 BitWise Operator

& --Bitwise And

|  Bit Wise Or

^ Bit wise XOR

<< Bit wise Left Shift

 >> Bitwise Right Shift


Logical Operator

&&--> Logical And

||--- > Logical OR

! Logical Not

Assignment Operator

= Assign

+= Add And Assign

- = Substract and Assign

*= Multiply and Assign

/ = Divide and Assign

%= Module and Assign


Special Operators in Type Script

 Ternary Operator ( ? : )

Syntax

let pin: number=4040;

console.log(pin==4040 ? "valid" : "invalid" )


Delete operator

It is used to delete a property from any specified object.

let product : any ={

Name : 'TV',

price : 333

}

delete product.price   //valid

console.log("price= " + product.price);  //undefined

Note: You cannot delete read only properties

delete Math.PI  //Invalid


In operator

It is used to verify whether the given property is available in an object .It returns true if found

Syntax

console.log("price"  in products)  //true  -- if price is found

In is used to verify the properties


OF operator

It is an special operator used to verify the values in an object. It returns boolean true if they the values are in collection.

Ex:

let cities: string[] =["Delhi" , "Hyd" ]

for( var city of cities) {

console.log(city)

}

typeof operator

It is an special operator that is used to identity and return data type of a property in an object.

Example

let product : any= {
    Id:1,
    Name: "TV",
    Isinstock : true
    }
    console.log("Id=" + typeof product.Id  + "\n"  +
     "Name=" + typeof product.Name + "\n" +
     "Isinstock=" + typeof product.Isinstock);

Output:




Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...