TypeScript Accessor

In TypeScript, there are two supported methods getter and setter to access and set the class members. The greater method control over how a member is accessed on each object. 
Methods of the typescript accessor property: 
 

  • getter: This method comes when you want to access any property of an object.
  • setter: This method comes when you want to change any property of an object.

getter: For extracting the value of a variable getter accessor property is the conventional method. It is denoted by get keyword, in an object literal. 
Syntax: 
 

get accessName() {  
    // getter, the code executed on getting obj.accessName  
  },  

Example: 
 

javascript




class MyClass {
    private _with:number = 5;
    private _height:number = 10;
    get square() {
        return this._with * this._height;
    }
}
console.log(new MyClass().square);


Output: 
 

50

A getter can be public, protected, private. It is just artificial to make something behave like a property or a function. So, get square() and new MyClass().square is the same as square() and new MyClass().square().
Setter: For updating the value of a variable the setter accessor property is the conventional method which is used. They are denoted by set keyword in an object literal.
Syntax: 
 

set accessName(value) {  
    // the code executed on setting 
    //obj.accessName = value, from setter  
  }  

Example: 
 

javascript




set fullname {
    const parts = value.split ('');
    this.partname = firstname[0];
    this.partname = firstname[1];
}
person fullname = "Hitangshu Agarwal"
console.log(person);


output: 
 

firstname: "Hitangshu"
lastname: "Agarwal"

Below example illustrates the concept of getter and setter clearly:
Example: 
 

javascript




const company = {
    companyName = "w3wiki",
    companyTag = "Edutech",
     
    // Function that return the Full description
    // combined both comapnyName and companyTag
    get full_Desc () {
        return `${company.companyName} ${company.CompanyTag}`
    },
     
     
    // It will return separately companyName and companyTag
    set full_Desc(value) {
        const parts = value.split ('');
        this.partname = companyName[0];
        this.partname = CompanyTag[1];
    }
};
 
company.full_Desc = "w3wiki Edutech";
console.log(company);


Output: 
 

w3wiki Edutech

Point To Be Remember: 
 

  • We achieved a proper control over, how a member is accessed on each object with the help of getter and setter.
  • TypeScript accessors require to set the compiler to output ECMAScript 5 or higher we should require typescript accessor. It does not support below ECMAScript 5.
  • Accessor with a get and no set property are automatically assumed to be read-only no need for manual work. This is helpful when we are generating a .d.ts file from our code.