Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to use getters/setters in TypeScript ?

How to use getters/setters in TypeScript ?

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 the 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 languages like Java, C++, etc. where you can only access variables via the getter or setter method, 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 the 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, the getter accessor property is the conventional method. It is denoted by the get keyword, in an object literal. A getter can be public, protected, or private.

Syntax:

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

Example: In this example, we will see the use of the Getter Method.

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 class
let student = new Student();
 
// Getter call
let 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: In this example, we will see the use of the setter method.

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 class
let student = new Student();
 
// Setter call
student.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 class
let student = new Student();
 
// setter call
student.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: In this example, we will see the use of Getter and Setter Method using Constructor.

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 call
student.course = "Data structure";
 
// Getter call
console.log("Course purchased is " + student.courses);


Output:

RELATED ARTICLES

Most Popular

Recent Comments