TypeScript 基础指南:存取器(Accessors)

在 TypeScript 中,存取器(Accessors)是一种特殊的类成员,它包括 get 和 set 方法。它们用于控制对类属性的访问和赋值过程。 存取器的基本语法如下:

class ClassName {
  private _property: type;

  get property(): type {
    // getter 方法
    return this._property;
  }

  set property(value: type) {
    // setter 方法
    this._property = value;
  }
}

在这个例子中:

1.
_property 是一个私有属性,它是存取器的后备存储。
2.
get property() 是 property 属性的 getter 方法,它返回 _property 的值。
3.
set property(value) 是 property 属性的 setter 方法,它将传入的 value 赋值给 _property。
使用存取器的好处包括:
控制属性的访问
通过 getter 和 setter 方法,可以控制对属性的读取和赋值操作,实现数据封装。
数据验证
在 setter 方法中可以对赋值进行检查和验证,确保数据的合法性。
计算属性
getter 方法可以根据其他属性的值动态计算并返回属性值。
兼容性
将属性改为存取器可以保持类的 API 不变,增强代码的可维护性。

下面是一个更加具体的示例:

class BankAccount {
  private _balance: number = 0;

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

  set balance(amount: number) {
    if (amount < 0) {
      console.log("Invalid amount. Balance cannot be negative.");
    } else {
      this._balance = amount;
    }
  }

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

  withdraw(amount: number): boolean {
    if (amount <= this.balance) {
      this.balance -= amount;
      return true;
    } else {
      return false;
    }
  }
}

let account = new BankAccount();
account.deposit(1000);
console.log(account.balance); // 输出: 1000
account.withdraw(500);
console.log(account.balance); // 输出: 500
account.balance = -100; // 输出: "Invalid amount. Balance cannot be negative."

在这个例子中:

1.
BankAccount 类有一个私有属性 _balance,用于存储账户余额。
2.
balance 属性是一个存取器,它的 getter 方法返回 _balance 的值,setter 方法检查并设置 _balance 的值。
3.
deposit 和 withdraw 方法分别增加和减少账户余额,在 withdraw 中使用了 balance 的 getter 方法进行余额检查。

通过使用存取器,我们可以在不破坏类 API 的情况下,对类属性的访问和赋值过程进行控制和验证。这有助于创建更加健壮和安全的类设计。