TypeScript Accessor

In TypeScript, the accessor property offers a mechanism for retrieving and modifying class attributes. It includes two methods outlined below.

  • getter
  • setter
  • getter

The getter accessor property is the standard approach for obtaining the value of a variable. In an object literal, the getter property is indicated by the "get" keyword. It may be classified as public, private, or protected.

Syntax

Example

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

Example

Example

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 standard approach employed to modify the value of a variable. In an object literal, the setter property is indicated by the "set" keyword.

Syntax

Example

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

Example

Example

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.

The following example illustrates the idea of getters and setters.

Example

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);
}

Output:

At this point, if we modify the initial line to: let passcode = "secret_passcode";

Subsequently, Output: Unauthorized modification of student information!

Naming convention for getter and setter

The nomenclature for the setter and getter methods ought to adhere to the subsequent guidelines:

getXX and setXX

In this context, XX refers to the variable's designation. For instance:

Example

private String name;

Then the setter and getter will be:

Example

public void setName(String name) { }
public String getName() { }

Input Required

This code uses input(). Please provide values below: