close
close
ts 瑁呴グ鍣 .value before after

ts 瑁呴グ鍣 .value before after

2 min read 23-10-2024
ts 瑁呴グ鍣 .value before after

Understanding TypeScript's get and set Accessors: A Deep Dive with Practical Examples

TypeScript, a powerful superset of JavaScript, allows developers to define custom properties with getter and setter methods, known as accessors. This feature empowers you to control how a property is accessed and modified, ensuring data integrity and adding flexibility to your code. This article delves into the concepts of get and set accessors, exploring their functionality and providing real-world examples to illustrate their benefits.

What are Accessors?

Accessors are special methods within a class that provide a controlled way to read and write property values. They offer an alternative to directly accessing and manipulating the property.

Getter Methods:

  • Responsible for retrieving the value of a property.
  • Return the desired value when the property is accessed.
  • Example: get name() { return this._name; }

Setter Methods:

  • Responsible for modifying the value of a property.
  • Receive the new value as an argument.
  • Update the underlying property with the new value.
  • Example: set name(newName: string) { this._name = newName; }

Why Use Accessors?

  • Data Validation: Enforce data integrity by validating input before assigning it to the property.
  • Calculated Properties: Derive values from other properties or external sources, providing dynamic behavior.
  • Enhanced Code Readability: Clear separation between data access and manipulation.
  • Data Encapsulation: Hide implementation details and control access to internal variables.
  • Improved Maintainability: Modifications are easier to manage as changes are localized within the accessors.

Practical Examples

Example 1: Data Validation

class User {
  private _age: number;

  get age(): number {
    return this._age;
  }

  set age(newAge: number) {
    if (newAge >= 0) {
      this._age = newAge;
    } else {
      console.error("Age cannot be negative.");
    }
  }
}

const user = new User();
user.age = 30; // Valid assignment
user.age = -10; // Invalid assignment, error will be logged

In this example, the age property uses a setter to ensure that only valid, non-negative ages are accepted. This prevents potential data inconsistencies.

Example 2: Calculated Properties

class Rectangle {
  private _width: number;
  private _height: number;

  constructor(width: number, height: number) {
    this._width = width;
    this._height = height;
  }

  get area(): number {
    return this._width * this._height;
  }
}

const rectangle = new Rectangle(5, 10);
console.log(rectangle.area); // Output: 50

Here, the area property is calculated using the width and height properties. It provides a dynamic and read-only value, making it convenient to access the area without explicitly calculating it.

Example 3: Encapsulation

class BankAccount {
  private _balance: number;

  get balance(): number {
    return this._balance;
  }

  deposit(amount: number) {
    this._balance += amount;
  }

  withdraw(amount: number) {
    if (this._balance >= amount) {
      this._balance -= amount;
    } else {
      console.error("Insufficient funds.");
    }
  }
}

const account = new BankAccount();
account.deposit(1000); // Deposit funds
console.log(account.balance); // Output: 1000
account.withdraw(500); // Withdraw funds
console.log(account.balance); // Output: 500

In this case, the _balance property is hidden from external access, and only the deposit and withdraw methods can modify its value. This ensures controlled interactions with the account's balance.

Key Takeaways

  • Accessors provide a powerful way to manage property access and manipulation in TypeScript.
  • get accessors control how property values are read.
  • set accessors control how property values are written.
  • Accessors enhance code readability, data integrity, and maintainability.
  • Consider using accessors when you need to validate data, derive values, or encapsulate internal variables.

By utilizing accessors, you can write cleaner, more robust, and maintainable TypeScript code, ensuring data integrity and providing a better developer experience.

Related Posts