In Typescript, Accessors are a way to control the access (getters) and modification (setters) of a class property.
Accessors are defined using the "get" and "set" keywords within a class.
They allow us to execute custom logic when getting or setting the value of a property.
The `getters` and `setters` provide a way to encapsulate the access, data and methods into a single unit.
It allows us to define custom behaviour when getting and setting values, providing better control over how data is accessed and modified.
Create class, make attributes private, no exposure to the outside world. syntax for defining attributes with prefix `_variableName`.
class Department { private _deptNo: number; }
get deptNo(): number { console.log("Getter Function called", this._deptNo) return this._deptNo; } set deptNo(value: number) { console.log("Setter Function called", value) if (value > 0) { this._deptNo = value; } else { console.error("deptNo must be greater than 0."); } }
let dept = new Department(); dept.deptNo = 1007;
Create setter and getter methods using `set` and `get` keywords before the function name.
To access any attributes of the `Department` class, we can simply create instance of Department class and with the help of dot `.`. we can `set` attribute value or `get` attribute value.
The above code will invoke the set deptNo Method and assign value to private attribute inside class `_deptNo`.
class Department { private _deptNo: number; get deptNo(): number { console.log("Getter Function called", this._deptNo) return this._deptNo; } set deptNo(value: number) { console.log("Setter Function called", value) if (value > 0) { this._deptNo = value; } else { console.error("deptNo must be greater than 0."); } } } let departmentInstance = new Department(); // Using the setter departmentInstance.deptNo = 1007; // Using the getter console.log(`Department No: ${departmentInstance.deptNo}`); // Output: "Department No: 1007"
The setter methods modify the property’s value. A setter function is also known as a mutator. while The getter methods return the value of the property’s value. A getter function is also called an accessor.
The "Department" class has a private property "_deptNo", and accessors (get deptNo() and set deptNo(value: number)) are used to control the access and modification of this property.
When we assign value to `departmentInstance.deptNo = 1007`, the `deptNo` setter method is invoked.
After that, we try to access the value of `departmentInstance.deptNo `, it will invoke the `get method` of `deptNo`.