How to use getters/setters in TypeScript ?

26 Jul, 2021
In TypeScript, there are two supported methods getter and setter to access and set the class members. In this very short article, I’m going to show you Typescript Accessor which includes getters/setters method.
Actually, getters and setters are nothing but a way for you to provide access to the properties of an object. Unlike other OOP’s languages like Java, C++, etc. where you can only access variables via the getter or setter method, but things work differently in Typescript where you can access variables directly (Given in the below example). This is called TypeScript Accessor.
Methods of the Typescript accessor property: 
getter: This method comes when you want to access any property of an object. A getter is also called an accessor.
setter: This method comes when you want to change any property of an object. A setter is also known as a mutator.
Below given code is a Student class with 3 properties: name, semester and course.
class Student {
    public name: string;
    public semester: number;
    public course: string;
}
 
To access any property of the Student class:
let student = new Student();

// You can access Student class variables directly
Student.name = "Aman Rathod";
Getter Method:
Note: For extracting the value of a variable, getter accessor property is the conventional method. It is denoted by get keyword, in an object literal. A getter can be public, protected, private.
Syntax:
get accessName() {  
    // getter, the code executed on 
    // getting obj.accessName  
}
Example:
Javascript
class Student {      private _name: string = "Aman Rathod";    private _semester: number;    private _course: string;      // Getter method to return name of    // Student class    public get name() {        return this._name;    }  }  // Access any property of the Student classlet student = new Student();  // Getter calllet value = student.name;  console.log(value);
Output:
Aman Rathod
From the above example you can observe that when we invoke the getter method (student.name), we didn’t include the open and close parentheses as we would with a regular function. Thus you access variables directly.
Setter Method: For updating the value of a variable the setter accessor property is the conventional method which is used. They are denoted by a set keyword in an object literal.
Syntax:
set accessName(value) {  

    // The code executed on setting 
    // obj.accessName = value, from setter  
}  
Example:
Javascript
class Student {      private _name: string = "Aman Rathod";    private _semester: number;    private _course: string;      // Getter method to return name    // of Student class    public get name() {        return this._name;    }      // Setter method to set the semester number    public set semester(thesem: number) {        this._semester = thesem;    }      // Setter method    public set course(thecourse: string) {        this._course = thecourse;    }}  // Access any property of the Student classlet student = new Student();  // Setter callstudent.semester = 5;student.course = "Web Development";
From the above example, also you can notice that call to the setter method doesn’t have parentheses like a regular method. When you call student.semester or student.course, the semester or course setter method is invoked and value is assigned. 
Handle Error: You can also add a condition in the setter method and if the condition is invalid then it throws an error. Let’s understand through the below example.
Javascript
class Student {        private _name: string = "Aman Rathod";    private _semester: number;    private _course: string;          // Suppose the only 1st to 8th-semester students    // are allowed to purchase the courses.    public set semester( thesem: number ) {                  if( thesem < 1 || thesem > 8 ){            throw new Error('Sorry, this course is valid for students from 1st to 8th semester');        }                      this._semester = thesem;    }}  // Access any property of the Student classlet student = new Student();  // setter callstudent.semester = 9;
Output:
Constructor: Now let’s discuss Getter and Setter Method using Constructor. Actually, there is no difference in using or not using constructor in a class to access getter or setter method, but we just want to give overlook of constructor in TypeScript.
Example:
Javascript
class Student {    name: string;    semester: number;    course: string;          constructor(nm: string, sm: number, cs: string) {        this.name = nm;        this.semester = sm;        this.course = cs;    }          // Getter method     public get courses() {        return this.course;    }          public set courses( thecourse: string) {        this.course = thecourse;    }}  // Access any property of the Student class, let student = new Student("Aman Rathod", 4, "Web Development" );   // Setter callstudent.course = "Data structure";  // Getter callconsole.log("Course purchased is " + student.courses);
Output:
JavaScript-Questions
Picked
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.