Typescript 类型脚本类型';字符串';不可分配给类型(枚举)

Typescript 类型脚本类型';字符串';不可分配给类型(枚举),typescript,Typescript,有问题 将枚举值分配给枚举属性时,出现错误:类型“string”不能分配给类型“CountryCode”。 我想我不应该得到它,因为属性和值都是相同的enum类型 具有enum属性的服务: @Injectable() export class UserData { private _country_code: CountryCode; private _currency_code: CurrencyCode; constructor() { } get country_co

有问题

将枚举值分配给枚举属性时,出现错误:
类型“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;
  }
}
this.userData.country_code = CountryCode[data.country_code];
枚举

export enum CountryCode {
  TH,
  BGD,
}
出现错误的用例:

@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;
  }
}
this.userData.country_code = CountryCode[data.country_code];

data.country\u code
可能已经是
CountryCode
类型,因此
this.userData.country\u code=data.country\u code应该足够了。调用
CountryCode[…]
在整数和字符串表示之间转换:

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

是为
enum CountryCode{…}

编译的代码,TypeScript中的枚举被转换为普通对象:

CountryCode[CountryCode["TH"] = 0] = "TH";
CountryCode[CountryCode["BGD"] = 1] = "BGD";
接下来,有两种方法可以使用它们:

name:  CountryCode.TH <-- 0    (number)
index: CountryCode[0] <-- 'TH' (string)
                               ^^^^^^^
但后者没有多大意义