TypeScript Accessor

In TypeScript, the accessor property provides a method to access and set the class members. It has two methods which are given below.

  1. getter
  2. setter

Getter

The getter accessor property is the conventional method which is used for retrieving the value of a variable. In object literal, the getter property denoted by "get" keyword. It can be public, private, and protected.

Syntax
snippet
get propName() {
    // getter, the code executed on getting obj.propName
  },
Example
snippet
class MyDrawing {  
    length: number = 20;  
    breadth: string = 15;  
 
    get rectangle() {  
        return this.length * this.breadth;  
    }  
}  
console.log(new MyDrawing().square);

Setter

The setter accessor property is the conventional method which is used for updating the value of a variable. In object literal, the setter property is denoted by "set" keyword.

Syntax
snippet
set propName(value) {
    // setter, the code executed on setting obj.propName = value
  }
Example #1
snippet
set displayFullName { 
    const parts = value.split (''); 
    this.pname = firstname[0]; 
    this.pname = firstname[1]; 
} 
person displayFullName = "Abhishek Mishra"
console.log(student);
  • The getter and setter give us a way of having finer control over how a member is accessed on each object.
  • The TypeScript accessors require us to set the compiler to output ECMAScript 5 or higher. It does not support below ECMAScript 5.
  • The accessor which has a get property without any set property is automatically assumed to be read-only. It is helpful when we are generating a .d.ts file from our code.

We can understand the concept of getter and setter from the below example.

Example #2
snippet
let passcode = "secret passcode";

class Student {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Unauthorized update of student detail!");
        }
    }
}

let stud = new Student();
stud.fullName = "Virat Kohli";
if (stud.fullName) {
    console.log(stud.fullName);
}
TypeScript Accessor

Now, if we change the first line: let passcode = "secret_passcode";

Then, Output: Unauthorized update of student detail!

Naming convention for getter and setter

The naming convention of the setter and getter method should be as follows:

getXX() and setXX()

Here, XX is the name of the variable. For example:

Example #1
snippet
private String name;

Then the setter and getter will be:

Example #2
snippet
public void setName(String name) { }
public String getName() { }
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +