Introduction
If you are from a .NET background, you know that get and set are the two keywords which help you to write the most efficient and manageable code.
The same get and set are also available in TypeScript as it is from the same company - Microsoft.
What is Get and Set?
Get and Set are known as "auto properties" which are used to access the class variable. It helps you to execute the logic when accessing the variable.
- Get
As the name implies, Get is used for getting the variable, that means something needs to be returned from the Get block. This helps you to do something else when the variable is being accessed like logging or calling any other function before returning the variable.
- Set
As the name implies, Set is used for setting the variable.This helps you to do something else when the variable is being set, like checking variable (validating variable) before setting, logging, or calling other functions.
Let's understand it by example.
We have a class "Date" where month is the property of type int. Now, we want to make sure that when the month is being accessed, we need to log and only valid month should be set (month>0 && month<=12) .
Now, let's see how Get and Set help.
- public class Date
- {
- private int month = 7;
-
- public int Month
- {
- get
- {
- Console.writeLine("month is being accessed");
- return month;
- }
- set
- {
- if ((value > 0) && (value < 13))
- {
- month = value;
- }
- }
- }
- }
As you see in the above example - Get and Set are helping us to execute the code when the property is being accessed. Well, you can manually validate and execute some logic but this provides you with a more manageable, efficient, and secure option.
Get and Set in Typescript
Let's write the code for the above scenario in TypeScript.
- class CustomDate {
- private _month: number;
-
- get Month(){
- if (this._month != null) {
- return this._month;
- }
- }
-
- set Month(month: number) {
- if (month > 0 && month < 13) {
- this._month = month;
- }
- }
-
- }
Now, see how Get and Set are making the TypeScript code look good and be more manageable.
Before TypeScript, we had to write at least 50 lines of JavaScript code for doing the same thing. This is the reason I like TypeScript.
Thanks guys. I hope you liked it.