Updated April 5, 2023
Introduction to TypeScript Getter
TypeScript getter allows the user to have control of access to the properties of the class. This getter method returns the value of the property provided to the class. Also, TypeScript getter is known as an Accessor. This accessor property provides a method to access the class members. Property is the conventional method used for retrieving the variable value. It has one more setter method, also known as a mutator, which will access the class objects and set their values. As a whole, It comes into the picture when the user wants to access any property of the object class, and the TypeScript setter comes into the picture when the user wants to change any property of the object class.
Syntax of TypeScript Getter
Given below is the syntax:
get propertyName() {
// getter code executed to access property using object.
}
The syntax looks similar to that of C# or Java. A getter can be a public, private or protected class.
Let us see how TypeScript getter works with a small example.
Example:
Sample class and how properties are accessed.
Code:
class Employee {
public ID: number;
public name: string;
public designation: string;
}
Here we have a sample Employee class with properties: ID, name and designation. To access this public property of class Employee, we need to create an object for the class Employee, as below.
Code:
let employee = new Employee();
So, the employee is the object created for class Employee. Now, we need to access the property using the object, as below.
Code:
employee.ID = 1024;
In cases if the user assigns any sampleID from the user input/ any type of output, and to perform any pre-checks for ID value before assigning becomes a hectic work to check.
Hence, to avoid checking the validation, TypeScript uses getters that control the access to the class property.
Code:
public get id() {
return this.id;
}
- We need to change the access modifier for properties from public to private.
- We need to change the property of the class from id to _id;
- Getter and setter need to be created for validity check.
Examples of TypeScript Getter
Given below are the examples mentioned:
Example #1
Simple TypeScript getter sample.
Code:
class rectArea {
private _length:number = 5;
private _breadth:number = 2;
private _height:number = 6;
get rectangle() {
return this._length * this._breadth * this._height;
}
}
console.log('Rectangular area is ' + new rectArea().rectangle);
Output:
Example #2
TypeScript getter along with setter.
Code:
// @strict: false
class Employee {
private _name: string = "";
get name(): string {
return this._name;
}
set name(nameCheck: string) {
if (nameCheck && nameCheck.length > 8) {
console.log("Name has a max length of " + nameCheck.length);
}
this._name = nameCheck;
}
}
let employee = new Employee();
employee.name = "Karthicks";
if (employee.name) {
console.log(employee.name);
}
Output:
Example #3
TypeScript getter with validations.
Code:
class Employee {
private _id: number = 0;
private _name: string = '';
private _designation: string = '';
public get id() {
return this._id;
}
public set id(ID: number) {
if (ID <= 0 || ID >= 200) {
console.log('The ID is invalid');
}
this._id = ID;
}
public get name() {
return this._name;
}
public set name(theName: string) {
if (!theName) {
console.log('Invalid name.');
}
this._name = theName;
}
public get designation() {
return this._designation;
}
public set designation(theDesignation: string) {
if (!theDesignation) {
console.log('Invalid designation.');
}
this._designation = theDesignation;
}
public getFullName(): string {
return `${this.name} ${this.designation}`;
}
}
let employee = new Employee();
employee.id = 1024;
employee.name = 'Benoy';
employee.designation = 'TA';
console.log('These are employee data: Person ' + employee.name + ' with ID ' + employee.id + ' has a designation of ' + employee.designation);
Output:
It has control over how members are accessed using the class object. These accessors require the user to set the compiler for ECMAScript5 or higher output, which does not support less than ECMAScript5. Accessor with the only getter is assumed to be as read-only. Encapsulation is an important part of OOP and TypeScript. It can be used before a function name and encapsulate the logic, using private properties to manage the state. Data is always protected using TypeScript getter; hence, we can’t change the name but can only get values.
Look at the example below; we will try to change the name.
Example #4
Mutating class property.
Code:
class Student {
stuName;
section;
constructor(sn:string, ssn:string) {
this.stuName = sn;
this.section = ssn;
}
get studentName() {
return this.stuName + " " + this.section;
}
}
var s1 = new Student("John", "Doe");
// Mutating the class property here
s1.studentName = "narayani";
console.log('Student name: ' + s1.studentName);
Output:
Here, we are trying to change the name of the property, but it won’t work, with the compiler giving an error. To avoid this issue, we should use the TypeScript setter method, which allows us to change the value of the class property. This is a completely separate topic considering the topic seen here.
Conclusion
We have seen what TypeScript getter is and how this getter method is used to access the property value of the class using an object. We have seen the syntax required to be used for the getter method. I looked into few examples that will be useful for handson and have tried mutating the property’s name using getter, which is actually not possible.
Recommended Articles
We hope that this EDUCBA information on “TypeScript Getter” was beneficial to you. You can view EDUCBA’s recommended articles for more information.