The Getters and Setters are known as accessor properties in TypeScript. They look like normal properties but are actually functions mapped to a Property. We use “get” to define a getter method and “set” to define a setter method. The Setter method runs when we assign a value to the Property. The Getter method runs when we access the Property.
Table of Contents
What are Getters & Setters
The Getters and Setters are known as Accessor Properties in TypeScript.
The Properties of an object can be accessed in two ways. We can access them directly or through a function. Based on how we access them, the properties are classified as
- Data Properties
- Accessor Properties
The Data Property is mapped to a value. The value can be a primitive value, object, or function.
In the example below, the property color
is data property. We can access its value as car.color
or assign a new value to it using car.color="red";
1 2 3 4 5 6 7 8 | let car = { color: "blue", }; car.color="red"; console.log(car.color) //red |
The accessor property is not mapped to a value but to a function. We call this function as accessor function. It is the job of the function to store or retrieve the value.
The accessor function that retrieves the value of a property is known as the Getter method. We use the Get keyword to declare a Getter method.
The accessor function that assigns a value to a property is known as the Setter method. We use the Set keyword to declare a Setter method.
Creating Getters TypeScript
The following is the syntax of the getter method.
We use the get keyword followed by a function expression. The name of the function becomes the name of the property ( propName
in the example).
1 2 3 4 5 6 7 8 9 10 11 12 13 | let obj = { _propName:"", get propName() { // getter method // this code is executed when we access the property using // Example value = obj.propName return this._propName }, } |
The getter function executes when we read the value of the Property. Note that we cannot pass an argument to the getter method. The return value of the getter method becomes the value of the property access expression.
In the following example, color
is a getter property, while _color
is a regular Property. The color function returns the value of the _color
property.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var car = { _color: "blue", // Accessor Property with the name color get color() { //getter return this._color; }, }; console.log(car.color) |
We access the color
getter property just like any other Javascript Property. i.e. using the dot notation
1 2 3 | console.log(car.color) |
Note that although the color
is a function, we do not invoke it like a function i.e car.color()
. But access it just like a property i.e. car.color
Creating Setters TypeScript
To create a setter method, we use the set keyword followed by a function expression. The name of the function becomes the name of the property ( propName
in the following example). A ‘set’ accessor must have exactly one parameter.
The following is the syntax of the setter method.
1 2 3 4 5 6 7 8 9 10 | let obj = { set propName(value) { // setter method // the code is executed when we assign a value to the property // Example obj.propName = value } } |
The setter
method executes when we assign a value to the property. JavaScript invokes the setter method with the value of the right-hand side of the assignment as the argument. If the setter method returns a value then it is ignored.
In the following example, color
is a setter property, while _color
is a regular Property. The color
function accepts a value and updates the _color
property.
1 2 3 4 5 6 7 8 9 10 11 | var car = { _color: "blue", set color(value:string) { //setter method this._color=value; } }; car.color="red"; |
Getter & Setters
The combined syntax for creating both setter and getter is as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 | let obj = { _propName:"", get propName() { // getter method return this._propName; }, set propName(value:<datatype>) { //Setter Method } }; |
The example code using both getter & Setter is as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | var car = { //Regular Property //Also known as backing Property to color getter & setter property _color: "blue", // Accessor Property with the name color get color() { //getter return this._color; }, set color(value) { //setter this._color=value; } }; //Using the getter method console.log(car.color); //blue //Setting color. Runs the setter method car.color="red"; console.log(car.color); //red Accessing the property //You can also access the backing property console.log(car._color); //red |
When we access the car.color
the getter method executes and it returns the value of the _color
property.
We assign the car.color="red"
the setter method executes. Inside the setter method, we assign the value to the property _color
.
Notice that the color
accessor property behind the scene uses the _color
property to store the value. _color
property is the backing property of the color
accessor property. As a convention, we prepend the backing property with an underscore to indicate that _color
should not be accessed directly.
Note that you cannot use the same name for an accessor property and a regular property.
Since ES6, you can also use the computed property names in getters & setters also. Simply enclose the expression inside square brackets( []
).
Getter & Setters in TypeScript Classes
We can create getters and setters in TypeScript classes, in the same way, we create them in TypeScript objects.
In the Typescript Classes, we can use the private access Modifier and mark the backing property as private.
In this example, we use the TypeScript class to create a Car
class, with getter and setter methods for the color
property. We marked the backing property _color
as private
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Car { //Regular Property //Also known as backing Property to color getter & setter property private _color:string="blue" // Accessor Property with the name color get color() { //getter return this._color; } set color(value) { //setter this._color=value; } }; let car = new Car() //Using the getter method console.log(car.color); //blue //Setting color. Runs the setter method car.color="red"; console.log(car.color); //red Accessing the property //Compiler error here console.log(car._color); //Property '_color' is private and only accessible within class 'Car' |
Marking the backing property _color
as private ensures that we do not accidentally modify its value directly. The Compiler throws the error Property <propertyName> is private and only accessible within class <className>
.
Using Getters & Setters
Use getter
or setter
only when you need a specific functionality provided by them.
There is no need to use accessor methods if you are simply using them to get or set the data property as in the example below. Plain property access is a better option here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Person { private _name="" constructor(name:string) { this._name=name; } get name() { return this._name; } set name(value) { this._name = value; } }; let p = new Person("Elisabet Leonzio"); p.name="Goranka Rafael" |
But there are some use cases, where you can think of using the Getters & Setters.
Validating values
In the example below, we want to limit the rate field to 10, if the user assigns any rate above 10. This can be easily achieved by a setter method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class IntCalculator { private _rate= 0 get rate() { return this._rate; } set rate(value:number) { if (value > 10) { console.log("Invalid Rate"); value = 10; } else if (value < 0) { console.log("Invalid Rate"); value = 0; } this._rate = value; } }; let calc = new IntCalculator() calc.rate = 5; console.log(calc.rate); //5 calc.rate = 10; console.log(calc.rate); //10 calc.rate = 100; console.log(calc.rate); //10 calc.rate = -1; console.log(calc.rate); //0 |
Another use case is to log the values as the property is being read or written.
Read-only /Write-only Properties
We can use the Setters & getters to create read-only or write-only properties.
If the property has only a getter method, then it is a read-only property. If it has only a setter method then it is a write-only property
In the following example, we only define a get method, making the color property read-only. Setting the color property using an assignment ( car.color="red";
) will result in a Compiler error and also an error while running the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Car { private _color="blue" get color() { return this._color; } }; let car = new Car(); console.log(car.color); //blue //Setting color. But it wont work as it is read only. car.color="red"; console.log(car.color); //blue //TypeScript Compiler error //Cannot assign to 'color' because it is a read-only property. //Runtime error while running the code //Cannot set property color of #<Object> which has only a getter |
Similarly, you can create a write-only property by only defining the setter method. Any attempt to read the write-only property always returns undefined.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Car { private _color= "blue" set color(value:string) { this._color=value } }; let car = new Car(); //Color is write only. Hnece always returns undefined console.log(car.color); //undefined car.color="red"; console.log(car.color); //undefined //Property '_color' is private and only accessible within class 'Car'. console.log(car._color); //red |
There isn’t a single line of typescript in this entire tutorial