如何使设置工具在打字稿中为可选?

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

我拥有的是一个旨在在屏幕上代表一个值的类:

export class Category() {
  constructor() {}
  private _name?: string;
  private _viewValue?: string;

  get name() {
    return this._name;
  }
  set name(value: string) {
    this._name = value;
    this._viewValue = getViewValue(name);
  }
  get viewValue() {
    return this._viewValue;
  }
  set viewValue (value: string) {
    this._viewValue = value;
  }
}

function getViewValue(value: string): string {
  switch (value) {
    case 'a1': {
      return 'A1';
    }
    case 'a1': {
        return 'A2';
    }
  }
}

但是,当我尝试设置此值时,它要求我为viewValue属性设置一个值。我想做的是使set viewValue(value)为可选,就像我对_name_value所做的那样。

我已经尝试过set? viewValue(value)set viewValue?(value)set viewValue(value)?,但这些都不起作用。

而且我当然可以使viewValue设置器什么也不做,但是使设置成为可选项真的不可能吗?

typescript typescript2.0
1个回答
1
投票

只是不要写二传手。但是category.viewValue = ''将引发错误。您可以使用公共属性viewValue,而无需使用getter / setter。

[有不同种类的属性描述符(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)。您不能混合数据和访问描述符。

export class Category() {
  constructor() {}
  private _name?: string;

  viewValue?: string;

  get name() {
    return this._name;
  }

  set name(value: string) {
    this._name = value;
    this.viewValue = getViewValue(name);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.