In TypeScript, the accessor property provides a method to access and set the class members. It has two methods which are given below.
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.
get propName() { // getter, the code executed on getting obj.propName },
class MyDrawing { length: number = 20; breadth: string = 15; get rectangle() { return this.length * this.breadth; } } console.log(new MyDrawing().square);
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.
set propName(value) { // setter, the code executed on setting obj.propName = value }
set displayFullName { const parts = value.split (''); this.pname = firstname[0]; this.pname = firstname[1]; } person displayFullName = "Abhishek Mishra" console.log(student);
We can understand the concept of getter and setter from the below example.
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); }
Now, if we change the first line: let passcode = "secret_passcode";
Then, Output: Unauthorized update of student detail!
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:
private String name;
Then the setter and getter will be:
public void setName(String name) { } public String getName() { }