Skip to content
Related Articles

Related Articles

TypeScript Accessor

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 17 Nov, 2021

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. 

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



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



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.

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



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


firstname: "Hitangshu"
lastname: "Agarwal"

Below example illustrates the concept of getter and setter clearly:


const company = {
    companyName = "GeeksforGeeks",
    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 = "GeeksforGeeks Edutech";


GeeksforGeeks 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.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!