Javatpoint Logo
Javatpoint Logo

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

Example


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

Example


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

Output:

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:

Then the setter and getter will be:






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA