Javatpoint Logo
Javatpoint Logo

TypeScript Accessor

The TypeScript accessor property has two methods. These are:

  1. getter
  2. setter

getter

The getter accessor property is the conventional method which is used for retrieving the value of a variable. In an object literal they are denoted by get keyword.

Syntax

Setter

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

Syntax

Note:

  • 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 with a get and no set property are automatically assumed to be readonly. This is helpful when we are generating a .d.ts file from our code.

Example

Output:

Virat Kohli

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 setter and getter method should be as follows:

        getXXX() and setXXX()

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

Then the setter and getter will be:





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA