Access Modifiers in TypeScript

  • We can control the access and visibility of data members of a class to the data members of other class using Access Modifiers.
  • Hence, we can restrict the usage of data members of a class outside of its scope.
  • This phenomena is known as Data Hiding or Encapsulation.
  • This concept is used with Inheritance in Classes.
Access Modifier Description
public We can access these data members from anywhere within our program. By default, all the data members are public.
private We can access these data members only from within the scope of the class. If we try to use them from outside, it will throw an error.
protected These data members can be used from within the scope of the class in which it is defined, and also from its child classes.

Below is an example to illustrate the access modifiers

class ParentClass { 
    pubStr:string;
    private prvStr:string;
    protected protStr:string;
 } 
  
 class ChildClass extends ParentClass { 

    display():void { 
       console.log("\nDisplay method in Child Class!");
       //this.prvStr = "Private Data Member";
       this.protStr = "Protected Data Member in Child Class";
       console.log(this.pubStr);
       console.log(this.protStr);
    } 
}
var childObject = new ChildClass();
childObject.pubStr = "Public Data Member in Child Class";
//childObject.protStr = "Protected data Member";
//childObject.prvStr = "Protected data Member"; 
childObject.display();

Below is the output of above code

Below are the errors if we try to access private and protected data members outside of their scope. I have put comments in the above code. I will be removing these comments and will show you the error message in a screenshot.

Let’s see the error messages after removing the comments of the private access modifiers.


We cannot access private data members from anywhere outside of that class.

Let’s see the error messages after removing the comments of the protected access modifiers.

We can access the protected data members from within the child class only.

instanceof Operator in TypeScript

  • instanceof operator returns a boolean value.
  • It returns true if the specified object belongs to the specified Class.

Below is an example

class Car { 
    model:string;  
    carDetails():void{
        console.log("car is alloted!");
    }
}
class Bike{color:string}
var myCar = new Car();
console.log(myCar instanceof Car);
console.log(myCar instanceof Bike);

Below is the output of above code

static Keyword in TypeScript

  • static keyword is applied to the fields or methods of a Class.
  • static field retains its value till the program finishes execution.
  • There is no need to create an object to access the data members (fields or methods) of a class. They can be directly accessed by the name of the class. For example, ClassName.DataMember;

Below is an example related to static keyword and how we can use it.

  class Car { 
    static dealer:string;
    model:string;
    static allocationDetails():void{
        console.log("Car is alloted!");
    }     
    carDetails():void{
        console.log(this.model + " is available with " + Car.dealer);
    }
 }
 var myCar = new Car();
 myCar.model = "Hyundai Creta";
 Car.dealer = "ABC Sales";
 myCar.carDetails();
 Car.allocationDetails();

Below is the output of above code

Method Overriding in TypeScript

  • Method Overriding is a concept of Inheritance in Classes where a child class can override a function of a parent class. In this, child class may or may not use the logic of a function defined in parent class.
  • We use super keyword to refer to the functions or fields of the immediate parent class.

Below is an example of method overriding USING super. If we use super, the same method of parent class is executed.

class ParentClass { 
    display():void {
       console.log("Display method from Parent Class!") 
    } 
 } 
 
 class ChildClass extends ParentClass { 
    display():void { 
       super.display() 
       console.log("dislay method from Child Class!")
    } 
    hello():void{
        console.log("Hello from Child Class!");
    }
 } 
 
 var parentObj = new ParentClass();
 parentObj.display();
 var childObj = new ChildClass();
 childObj.display();
 childObj.hello();

Below is the output of above code

Below is an example WITHOUT using super. If we skip super, then that method of parent class is not executed. Only the method of child class is executed.

class ParentClass { 
    display():void {
       console.log("Display method from Parent Class!") 
    } 
 } 
 
 class ChildClass extends ParentClass { 
    display():void { 
       //super.display() 
       console.log("dislay method from Child Class!")
    } 
    hello():void{
        console.log("Hello from Child Class!");
    }
 } 
 
 var parentObj = new ParentClass();
 parentObj.display();
 var childObj = new ChildClass();
 childObj.display();
 childObj.hello();

Below is the output of above code

Inheritance in TypeScript

  • Inheritance is a concept in which we reuse the properties and methods of another class or interface, hence no need to rewrite the code again and again.
  • We use extend keyword to inherit other interfaces and classes.
  • We use an existing class to create a new class.
  • The class that is used to create the new class is called as parent class/super class. The newly created class is called as child class/sub class.
  • Child class inherits all the fields and methods from the parent class except the private fields and constructor.
  • Inheritance with Interface is explained in another article.

Syntax

class childClass extends parentClass{}

Below is an example of class inheritance

class Vehicle{
    model:string;
    color:string;
}
class Car extends Vehicle{
    fuelType:string;
}

class Maruti extends Car{
    customername:string;
    purchasedOn:string;
    
    constructor(custName:string, date:string, ){
        super();
        this.customername = custName;
        this.purchasedOn = date;   
    }
    purchaseDetails():void {
        console.log(this.customername + " purchased a car on " + this.purchasedOn);
        console.log("Model of the car: " + this.model+ "; Color: " + this.color + "; Fuel Type: " + this.fuelType);
    }
}
var car = new Maruti("Akanksha","28th Dec, 2018");
car.model = "Maruti Suzuki Dzire"
car.fuelType = "Diesel";
car.color = "Silver";
car.purchaseDetails();

Below is the output of above code

Other Related Articles

Classes in TypeScript
Interfaces and Classes in TypeScript
Interfaces in TypeScript
Access Modifiers
Method Overriding

Interface and Classes in TypeScript

Let’s implement Interfaces to Class.
Below is an example

interface IVehicle{
    model:string;
    color:string;
}
interface ICar extends IVehicle{
    fuelType:string;
}

class Car implements ICar{
    customername:string;
    purchasedOn:string;
    mycar1:ICar;
    model:string;
    color:string;
    fuelType:string;
    
    constructor(custName:string, date:string, car1:ICar){
        this.customername = custName;
        this.purchasedOn = date;   
        this.mycar1 = car1;
    }
    purchaseDetails():void {
        console.log(this.customername + " purchased a car on " + this.purchasedOn);
        console.log("Model of the car: " + this.mycar1.model+ "; Color: " + this.mycar1.color + "; Fuel Type: " + this.mycar1.fuelType);
        // Below line of code will only return undefined
        //console.log("Model of the car: " + this.model+ "; Color: " + this.color + "; Fuel Type: " + this.fuelType);
    }
}
var carDetails:ICar = {model:"Hyundai Creta", color:"White", fuelType:"Petrol"};
var car = new Car("Akanksha","28th Dec, 2018", carDetails);
car.purchaseDetails();

Below is the output of above code

Other Related Articles

Interfaces in TypeScript
Classes in TypeScript
Inheritance in TypeScript

Classes in TypeScript

  • TypeScript is an Object Oriented Language and hence we can create classes, interfaces, objects etc. in TypeScript.
  • We can create objects of the classes, hence classes encapsulates the data for the object.
  • We use class keyword to create classes in TypeScript.
  • Class name follows the rules same as variables.
  • Class definition includes:
    • Fields: A field is a variable declared in a class. They represents the properties of the object creates using the class. These fields can only be used by the objects of that class and their scope is limited to that class only.
    • Constructors: Constructors are used to allocate memory for the objects of the class. We can also use constructors to assign values to the fields of the object. Please note that we can define only one constructor in a class, multiple constructor declaration is not allowed. A constructor is a function which can be parameterized.
    • Functions: These are the operations or actions that an object can perform. They are also referred as methods.
  • We do not use var keyword to declare fields in a class.
  • this keyword refers to the current instance of the class. If the field name and constructor’s parameter names are same, we can use this keyword with fields to remove the ambiguity.
  • We use new keyword to create an object of the class.
    • Syntax: var objectName = new ClassName();
  • In above piece of code, ClassName() invokes the constructor of the class. If the constructor has parameters, we can pass the value of those parameters from here. For example: var objectName = new ClassName(value1, value2,….);
  • We access the field and methods of the class using the object followed by dot(.). For example,
    • to access field: objectName.field1;
    • to access function: objectName.functionName(parameterValue1, parameterValue2,…);

Syntax for creating class

class className{
  // class fields and methods
}

Below is an example, where we create a class, define fields, constructor and function. We then create an object of this class, initialize the fields and then invoke the function.

class Car{
    customername:string;
    purchasedOn:string;

    constructor(custName:string, date:string){
        this.customername = custName;
        this.purchasedOn = date;
    }
    purchaseDetails():void {
        console.log(this.customername + " purchased a car on " + this.purchasedOn);
    }
}
var car = new Car("Akanksha","28th Dec, 2018");
car.purchaseDetails();

Below is the output of above code

Other Related Articles

Interfaces in TypeScript
Interface and Classes in TypeScript
Inheritance in TypeScript
static keyword
instanceof Operator
Access Modifiers

Interfaces in TypeScript

  • An INTERFACE provides a structure which defines properties and methods, which an entity must adhere to.
  • Interface contains only declaration part. The definition is provided by the deriving class/object.
  • The deriving class/object is responsible to provide the definition of all the members and methods that are declared in interface.
  • If the deriving class/object fails to do so, an error is displayed stating that a particular property or method is missing.
  • You can use an interface multiple times and with multiple values.

Below is an example of declaring an interface and creating an object for it.

interface IVehicle{
    // These are the two properties declared
    model:string; 
    color:string;
    allocationDetails:()=>any; // This is the method declaration, returning any data type
}
var car:IVehicle = {
    // Defining the two properties and a method of interface
    model:"Hyundai Creta",
    color:"White",
    allocationDetails: ():string =>{
        return "New car is allocated.";
    }
}
console.log("Model of the car: " + car.model);
console.log("Color of the car: " + car.color);
console.log(car.allocationDetails());

Below is the output of above code

Interface and Union

We can use Union in Interfaces to define properties and methods.
Below is a sample code to illustrate the same

interface IVehicle{
    model:string; 
    color:string;
    allocationDetails:string|string[]|(()=>string);
}

console.log("Invoking as String!");
var car1:IVehicle = {
    model:"Hyundai Creta",
    color:"White",
    allocationDetails:"New car is allocated."
}
console.log("Model of the car: " + car1.model);
console.log("Color of the car: " + car1.color);
console.log("Allotment Details: " + car1.allocationDetails);

console.log("\nInvoking as Array!");
var car2:IVehicle = {
    model:"Hyundai Creta",
    color:"White",
    allocationDetails: ["Alloted to Akanksha","She lives in Delhi"]
}
console.log("Model of the car: " + car2.model);
console.log("Color of the car: " + car2.color);
console.log("Allotment Details: " + car2.allocationDetails);

console.log("\nInvoking as Function!");
var car3:IVehicle = {
    model:"Hyundai Creta",
    color:"White",
    allocationDetails:()=>{
        return "New car is allocated.";
    }
}
console.log("Model of the car: " + car3.model);
console.log("Color of the car: " + car3.color);
var allocation:any = car3.allocationDetails;
console.log(allocation());

Below is the output of above code

Interface and Array

We can use arrays to define the parameters in an Interface.
Below is an example

interface IVehicle{
    [index:number]:string;
}

var carModels:IVehicle = ["Maruti Suzuki Ertiga","Maruti Suzuki Baleno","Hyundai Santro","Hyundai Creta"];
console.log("carModels[0]: " + carModels[0]);
console.log("carModels[1]: " + carModels[1]);
console.log("carModels[2]: " + carModels[2]);
console.log("carModels[3]: " + carModels[3]);
console.log("carModels[4]: " + carModels[4]); //Index out of range

Below is the output of above code

Interface and Inheritance

We can inherit single or multiple interfaces and reuse their properties or methods multiple times.
Below is a sample code

interface IVehicle{
    model:string;
    color:string;
}
interface ICar{
    fuelType:string;
}
//Multiple Inheritance
interface IMaruti extends IVehicle, ICar{}
var myCar:IMaruti = {  
    model:"Hyundai Creta",
    color:"White",
    fuelType:"Petrol"
}
console.log(myCar.model + " is now available in " + myCar.color + " color in " + myCar.fuelType + " Fuel Type.");

//Single Inheritance
interface IBike extends IVehicle{}
var myBike:IBike = {
    model:"TVS Apache",
    color:"Black"
}
console.log(myBike.model + " is now available in " + myBike.color + " color.");

Below is the output of above code

Other Related Articles

Classes in TypeScript
Interface and Classes in TypeScript
Inheritance in TypeScript

Union in TypeScript

Till now we have seen variable declaration with one data type, or we can declare a variable with any data type so that we can store values of any data type in that. We use UNION if we want to restrict the data type of variable to two or more data types.
We combine two or more data types using pipe symbol (|) to denote a Union type.
Syntax

var variable:type1|typ2|type3|...

Below is an example

var empID:number|string;
empID = 1001;
console.log("Emp ID as number: " + empID);
empID = "EMP1001";
console.log("Emp ID as string: " + empID);

Below is the output of above code

You can also pass union type in function parameters and can also use in Arrays.
Below is an example of passing Union as Parameter

var empID:number|string;
empID = 1001;
console.log("Passing number");
check(empID);
empID = "1001";
console.log("\nPassing String");
check(empID);
function check(EID:number|string):void{
    if(typeof(EID)=="number"){
        var nextEID = EID+1;
        console.log("Next Employee ID will be: " + nextEID)
    }
    else{
        console.log("Data Type is: " + typeof(EID));
    }
}

Below is the output of above code

Below is an example of Union in Arrays

var empID:number[]|string[];
empID = [10,20,30];
console.log("Display Numbers");
displayArray(empID);

empID = ["Delhi","Mumbai","Pune"];
console.log("\nDisplay String");
displayArray(empID);

function displayArray(EIN:number[]|string[]):void{
    var i:number;
    for(i=0; i<EIN.length; i++){
        console.log(EIN[i]);
    }
}

Below is the output of above code

Tuples in TypeScript

We have seen Arrays where we can store multiple values, but of same data type.
But what if we want to store values of different data types in an array. In this case, we do not use Arrays. We use TUPLES. We can also use tuples in function, the same way we used arrays. Index of tuples starts with 0(zero) and we can get the number of elements in a tuple by using length property.

Syntax
var tupleVariable = [value1, value2, value3,...];
Declare and initialize a tuple
// Declare and initialize a tuple in one statement
var person = ["Akanksha","Delhi",9876543210]; 

// Create empty tuple and then initialize it in another statement
var person1 = [];
person1[0] = "Akanksha";
person1[1] = "Delhi";
person1[2] = "9876543210";
Access tuple elements

Below is an example

var person = ["Akanksha","Delhi",9876543210];
var i;
for(i=0; i<person.length;i++){
    console.log(person[i]);
}

Below is the output of above code

push() and pop()

push() method is used to add an element at the end of a tuple, hence increasing the length of the tuple. pop() method removes and returns the last value of the tuple, hence reducing the length of the tuple.
Below is an example

var person = ["Akanksha","Delhi",9876543210];
var i;
console.log("Length of Tuple before PUSH: " + person.length);
console.log("Items before PUSH");
for(i=0; i<person.length;i++){
    console.log(person[i]);
}

person.push("Software Developer");
console.log("\nPUSH Operation Performed");
console.log("Length of Tuple after PUSH: " + person.length);
console.log("Items of tuple after PUSH");
for(i=0; i<person.length;i++){
    console.log(person[i]);
}

person.pop();
console.log("\nPOP Operation Performed");
console.log("Length of Tuple after POP: " + person.length);
console.log("Items of tuple after POP");
for(i=0; i<person.length;i++){
    console.log(person[i]);
}

Below is the output of above code

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started