如何通过封装在TypeScript中来保护和更改数组?

问题描述 投票:0回答:1

请考虑以下代码:

class Customers {
  private _list: Array<Person>;

  constructor() {
    this._list = [];
  }

  public get customerList(): Array<Person> {
    return this._list;
  }
}

给出该代码,似乎没有任何方法可以防止使用者以我可能不喜欢的方式更改customerList数组。例如,消费者可以致电

myCustomer.customerList.slice(1, 2);

并在没有“许可”的情况下删除客户。

用其他语言,我将列表显示为IEnumerable<T>,然后根据需要提供特定的删除方法。

如何在TypeScript中正确封装和保护'customerList()'属性?

(非常高兴地承认我正在以完全错误的方式进行此操作.....]

typescript encapsulation
1个回答
1
投票

TypeScript's ReadonlyArray<T>正是您要寻找的。该界面可防止客户端代码更改数组。

© www.soinside.com 2019 - 2024. All rights reserved.