Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Type 'string' is not assignable to type (enum)

Tags:

typescript

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];
like image 801
user1935987 Avatar asked Oct 18 '22 08:10

user1935987


1 Answers

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.

like image 65
SVSchmidt Avatar answered Oct 21 '22 05:10

SVSchmidt