请考虑以下代码:
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's ReadonlyArray<T>
正是您要寻找的。该界面可防止客户端代码更改数组。