5

Have an issue.

While assigning enum value to the enum attribute, getting an error: Type 'string' is not assignable to type 'CountryCode'. Which i suppose i shouldn't get cause both attribute and value are the same enum type

service with enum attribute:

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

usage case with an error:

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

2 Answers 2

4

enums in TypeScript are transpiled into plain objects:

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

Following of that, there is two ways you might use them:

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

The latter throws an error if you try to assign it to a variable of type CountryCode. So I believe this is what is happening here. See this example on typescript playground.

However, given the above output, this should work:

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

But the latter does not make that much sense.

Sign up to request clarification or add additional context in comments.

Comments

0

data.country_code is probably already of type CountryCode, therefore this.userData.country_code = data.country_code; should be enough. Calling CountryCode[...] converts between the integer and string representation:

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

is the compiled code for enum CountryCode {...}.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.