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 {
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 :
For any Help or Queries Contact us on info@crmonce.com or +918096556344