Get and Set in TypeScript
Last Updated :
09 Jan, 2024
In TypeScript, you can use the get
and set
keywords to define getter and setter methods within a class. These methods allow you to encapsulate the access and modification of class properties, providing a way to control and customize the behavior. In this article, we are going to learn to get and set in TypeScript.
Syntax:
Get
class ClassName {
private _propertyName: Type = /* initial value */;
// Getter method
get propertyName(): Type {
// Optional additional logic
return this._propertyName;
}
}
Set
class ClassName {
private _propertyName: Type = /* initial value */;
// Setter method
set propertyName(value: Type) {
// Optional validation or additional logic
this._propertyName = value;
}
}
Parameters:
ClassName
: The name of the class.
_propertyName
: The private property you want to expose with the getter or (modify with the setter).
Type
: The type of the property.
value:
Type
: The parameter in the setter representing the new value to set.
Example 1: In this example, the TemperatureConverter
class has properties for Celsius and Fahrenheit temperatures, get
and set
methods are used to convert between them. The setter methods include validation to ensure that the Celsius temperature is above the absolute zero limit.
Javascript
class TemperatureConverter {
private _celsius: number = 0;
get celsius(): number {
return this ._celsius;
}
set celsius(value: number) {
if (value >= -273.15) {
this ._celsius = value;
} else {
console.error(`Invalid temperature. Must be
greater than or equal to -273.15°C.`);
}
}
get fahrenheit(): number {
return ( this ._celsius * 9 / 5) + 32;
}
set fahrenheit(value: number) {
this ._celsius = (value - 32) * 5 / 9;
}
}
const temperatureConverter =
new TemperatureConverter();
temperatureConverter.celsius = 25;
console.log( "Temperature in Celsius:" ,
temperatureConverter.celsius);
console.log( "Temperature in Fahrenheit:" ,
temperatureConverter.fahrenheit);
|
Output:
Temperature in Celsius: 25
Temperature in Fahrenheit: 77
Example 2: In this example, the UserProfile
class has a username property with a minimum length requirement. The get
and set
methods are used to control access to the username, and the setter method validates the input length before setting the value.
Javascript
class UserProfile {
private _username: string = "" ;
get username(): string {
return this ._username;
}
set username(value: string) {
if (value.length >= 3) {
this ._username = value;
} else {
console.error(`Invalid username. Must
be at least 3 characters long.`);
}
}
}
const userProfile = new UserProfile();
userProfile.username = "JohnDoe" ;
console.log( "Username:" , userProfile.username);
userProfile.username = "JD" ;
console.log( "Username:" , userProfile.username);
|
Output:
Username: JohnDoe
Invalid username. Must be at least 3 characters long.
Username: JohnDoe
Share your thoughts in the comments
Please Login to comment...