TypeScript tutorial: Lesson 18 – Accessor


Accessor property
Support from ECMASCRIPT 5
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.
A getter can be public, protected, private.

Syntax:

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

Example:

class Rectangle{
  
  private _width:number
  private _height:number
  
  constructor(w:number,h:number){
    this._width = w
    this._height = h
  }

  get square(){
    return this._width*this._height
  }
}

console.log(new Rectangle(100,100).square)

Result:

[LOG]: 10000 

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 access_name(value) {  
    // the code executed on setting 
    //obj.access_name = value, from setter  
}  

Example:

const company = { 
    companyName : "tutorialspots", 
    companyTag : "com", 
      
    // Function that return the Full description 
    // combined both companyName and companyTag 
    get full_desc () { 
        return `${company.companyName} ${company.companyTag}` 
    }, 
            
    // It will return separetely companyName and companyTag 
    set full_desc(value) { 
        const parts = value.split (' '); 
        this.companyName = parts[0]; 
        this.companyTag = parts[1]; 
    } 
}; 
  
company.full_desc = "tutorialspots com"; 
console.log(company); 

Result:

[LOG]: { "companyName": "tutorialspots", "companyTag": "com", "full_desc": "tutorialspots com" } 

Leave a Reply