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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With