Search code examples
typescriptencapsulation

How do protect and array from being altered via encapsulation in TypeScript?


Consider the following code:

class Customers {
  private _list: Array<Person>;

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

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

Given that code, there doesn't appear to be any way to prevent a consumer to alter the customerList array in ways that I might not like. For instance, a consumer could call

myCustomer.customerList.slice(1, 2);

and remove customers without "permission".

In other languages I'd expose the list as an IEnumerable<T> and then provide specific removal methods if desired.

How do I properly encapsulate and protect the 'customerList()' property in TypeScript?

(Perfectly happy to admit I'm going about this the entirely wrong way.....)


Solution

  • The TypeScript's ReadonlyArray<T> is exactly what you are looking for. The interface prevents the client code from altering the array.