Typescript-typ 'string' kan inte tilldelas typen (enum)


Har ett problem.

När jag tilldelar ett enum-värde till enum-attributet får jag ett fel: Type 'string' is not assignable to type 'CountryCode'. Vilket jag antar att jag inte borde få eftersom både attributet och värdet är av samma enum-typ

tjänst med enum-attribut:

@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;
  }
}

enum

export enum CountryCode {
  TH,
  BGD,
}

användningsfall med ett fel:

this.userData.country_code = CountryCode[data.country_code];

Svar #1

enum i TypeScript transpileras till vanliga objekt:

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

Efter det finns det två sätt du kan använda dem på:

name:  CountryCode.TH <-- 0    (number)
index: CountryCode[0] <-- 'TH' (string)
                               ^^^^^^^

Den senare ger ett fel om du försöker tilldela det till en variabel av typen CountryCode. Så jag tror att detta är vad som händer här. Se detta exempel på TypeScript Playground.

Men med tanke på ovanstående resultat borde detta fungera:

this.userData.country_code = data.country_code;
OR
this.userData.country_code = CountryCode[CountryCode[data.country_code]];

Men det senare är inte särskilt meningsfullt.

Svar #2

data.country_code är troligtvis redan av typen CountryCode, därför borde this.userData.country_code=data.country_code; räcka. Att anropa CountryCode[...] konverterar mellan heltals- och strängrepresentationen:

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

är den kompilerade koden för enum CountryCode {...}.

Relaterade artiklar