Get Set in TypeScript

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.
  1. public class Date  
  2. {  
  3.     private int month = 7;  // Backing store  
  4.   
  5.     public int Month  
  6.     {  
  7.         get  
  8.         {  
  9.             Console.writeLine("month is being accessed");
  10.             return month;  
  11.         }  
  12.         set  
  13.         {  
  14.             if ((value > 0) && (value < 13))  
  15.             {  
  16.                 month = value;  
  17.             }  
  18.         }  
  19.     }  
  20. }  
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.
  1. class CustomDate {  
  2.     private _month: number;  
  3.   
  4.     get Month(){  
  5.         if (this._month != null) {  
  6.             return this._month;  
  7.         }  
  8.     }  
  9.   
  10.     set Month(month: number) {  
  11.         if (month > 0 && month < 13) {  
  12.             this._month = month;  
  13.         }  
  14.     }  
  15.       
  16. }  
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. 
Ebook Download
View all

Test

Read by 16 people
Download Now!
Learn
View all