Typescript类型“字符串”无法赋值给类型(枚举)。

5

有一个问题。

在给枚举属性分配枚举值时,出现错误:类型“string”不能赋值给类型“CountryCode”。我认为不应该出现这种情况,因为属性和值都是相同的enum类型。

enum属性的服务:

@Injectable()
export class UserData {
  private _country_code: CountryCode;
  private _currency_code: CurrencyCode;

  constructor() { }


  get country_code(): CountryCode {
    return this._country_code;
  }

  set country_code(value: CountryCode) {
    this._country_code = value;
  }
  get currency_code(): CurrencyCode {
    return this._currency_code;
  }
  set currency_code(value: CurrencyCode) {
    this._currency_code = value;
  }
}

枚举

export enum CountryCode {
  TH,
  BGD,
}

使用案例出现错误:

this.userData.country_code = CountryCode[data.country_code];
2个回答

4

TypeScript中的枚举被转译为普通对象:

CountryCode[CountryCode["TH"] = 0] = "TH";
CountryCode[CountryCode["BGD"] = 1] = "BGD";

接下来,您可以使用以下两种方式:
name:  CountryCode.TH <-- 0    (number)
index: CountryCode[0] <-- 'TH' (string)
                               ^^^^^^^

后者如果你试图将它分配给类型为CountryCode的变量,就会抛出错误。因此我认为这就是这里发生的事情。 在typescript playground上查看此示例。但是,考虑到上面的输出,这应该可以工作:
this.userData.country_code = data.country_code;
OR
this.userData.country_code = CountryCode[CountryCode[data.country_code]];

但是后者并没有太多意义。

0

data.country_code 可能已经是 CountryCode 类型,因此 this.userData.country_code = data.country_code; 就足够了。调用 CountryCode[...] 可以在整数和字符串表示之间进行转换:

CountryCode[CountryCode["TH"] = 0] = "TH";
CountryCode[CountryCode["BGD"] = 1] = "BGD";

这是编译后的代码:enum CountryCode {...}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接