vendredi 21 août 2020

typescript getter / setter on array property

Is there a good way to use getter / setter pattern for array properties?

For example:

export class User {

  private _name: string;

  set name(value: string) {
    this._name = value;
  }

  get name(): string {
    return this._name;
  }

  private _roles = new Array<string>();

  set roles(value: Array<string>) {
    this._roles = value;
  }

  get roles(): Array<string> {
    return this._roles;
  }

  constructor() {
  }
}

While changing user.name fires the setter method, adding or removing items from roles does not.

Now i think i understand why it does not fire the setter, because adding items to the array does not change the pointer but merely adds to the already allocated space (correct me if i'm wrong).

How can we get the desired getter / setter behaviour on array properties?

Aucun commentaire:

Enregistrer un commentaire