Introduction
TypeScript, a powerful superset of JavaScript, adds robust static types and other features to enhance development.
One such feature is getters and setters, which allow for controlled access to an object’s properties.
In this blog, we'll explore the concept of getters and setters in TypeScript, understand their benefits, and see some real-life examples to grasp their utility better.
What are Getters and Setters?
Getters and setters are special methods that provide controlled access to the properties of a class.
They are used to encapsulate the internal representation of an object and ensure data integrity.
Getters are methods that get the value of a property.
Setters are methods that set the value of a property.
Why Use Getters and Setters?
Encapsulation: Encapsulate the internal state and ensure it can only be modified in a controlled way.
Validation: Add validation logic when setting a property.
Computed Properties: Compute the value of a property on the fly.
Defining Getters and Setters
class User {
private _name: string;
constructor(name: string) {
this._name = name;
}
// Getter
get name(): string {
return this._name;
}
// Setter
set name(newName: string) {
if (newName.length > 0) {
this._name = newName;
} else {
console.error("Name cannot be empty.");
}
}
}
const user = new User("John Doe");
console.log(user.name); // Output: John Doe
user.name = "Jane Doe";
console.log(user.name); // Output: Jane Doe
user.name = ""; // Output: Name cannot be empty.
In this example, the User
class has a private property _name
, and we use a getter and setter to access and modify this property.
Readonly Properties
Sometimes, you may want a property to be read-only, meaning it can only be set once and not modified thereafter. Getters can help achieve this.
class User {
private _id: number;
private _name: string;
constructor(id: number, name: string) {
this._id = id;
this._name = name;
}
// Readonly Getter
get id(): number {
return this._id;
}
get name(): string {
return this._name;
}
set name(newName: string) {
if (newName.length > 0) {
this._name = newName;
} else {
console.error("Name cannot be empty.");
}
}
}
const user = new User(1, "John Doe");
console.log(user.id); // Output: 1
// user.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
Here, the id
property is read-only and cannot be modified once set in the constructor.
Real Life Example: Bank Account
Consider a bank account class where we want to control access to the balance property. We’ll use getters and setters to ensure the balance is updated correctly and cannot be set to a negative value.
class BankAccount {
private _balance: number;
constructor(initialBalance: number) {
this._balance = initialBalance;
}
// Getter
get balance(): number {
return this._balance;
}
// Setter
set balance(amount: number) {
if (amount >= 0) {
this._balance = amount;
} else {
console.error("Balance cannot be negative.");
}
}
deposit(amount: number): void {
if (amount > 0) {
this._balance += amount;
} else {
console.error("Deposit amount must be positive.");
}
}
withdraw(amount: number): void {
if (amount > 0 && amount <= this._balance) {
this._balance -= amount;
} else {
console.error("Invalid withdraw amount.");
}
}
}
const account = new BankAccount(1000);
console.log(account.balance); // Output: 1000
account.deposit(500);
console.log(account.balance); // Output: 1500
account.withdraw(200);
console.log(account.balance); // Output: 1300
account.balance = -500; // Output: Balance cannot be negative.
In this example, the BankAccount
class uses a getter and setter for the _balance
property to ensure it is always valid.
Conclusion
Getters and setters in TypeScript are powerful tools that allow for controlled access and modification of class properties.
They help encapsulate internal state, add validation logic, and compute properties on the fly.
By using getters and setters, you can create more robust, maintainable, and error-resistant code.
Thank You Everyone For The Read ....
Happy Coding! 🤞💻
👋 Hello, I'm Aaryan Bajaj .
🥰 If you liked this article, consider sharing it.