In this blog we  will see  how to use getters and setters in TypeScript .

Introduction :

Getters and setters are two terms that can be used in TypeScript to obtain and modify the values of class members.By using the dot operator with the object of the specific class as a reference, users can access the public members of the class directly. Using the getter method is all that is required to access the class’s private members.
 Using getters :

In other programming languages, such as C++ and Java, we would construct a method to access the class’s private members; in TypeScript, getters are utilised in place of those methods. By adding the get keyword before the declaration of the accessor method, which returns some value, we may create the getters.

Syntax : 

class student {
private std_Name: string = “surendra”;
public get name() {
return this.std_Name;
}
}

let boy = new student();
let name_Value = boy.name

Example :

class student {

   private std_Name: string = “Surendra”;
   private age_of_std: number = 19;
   private course: string = “Bsc”;
   
   public get name() {
      return this.std_Name;
   }
   public get age() {
      return this.age_of_std;
   }
}

 

let boy = new student();

 

let name_Value = boy.name;
console.log(“The name of the student is ” + name_Value);
console.log(“The age of the student is ” + boy.age);

Using setters :

In TypeScript, accepting the object as a reference prevents us from altering the value of the class’s secret members. We must therefore utilise setters. The setter functions like a standard method; but, in order to designate it as a setter, the’set’ keyword must be included before the method description.

Syntax : 

class student {
private std_Name: string = “Surendra”;
public set name(new_value) {
this.std_Name = new_value;
}
}

let boy = new student();
let boy.name = “surendra”;

Example : 

class student {
    private std_Name: string = “surendra”;
    private age_of_std: number = 19;
    private role: string = “Content Writer”;
    public get name() {
       return this.std_Name;
    }
    public set name(new_value: string) {
       this.std_Name = new_value;
    }
 }
 
 let man = new employee();
 
 let name_Value = man.name;
 console.log(“The name of the employee is ” + name_Value);
 man.name = “Jems Bond”;
 console.log(
    “The name of the employee after updating it using the setters is ” + man.name
 );

 

For any Help or Queries Contact us on info@crmonce.com or +918096556344