I have the following TypeScript enum:
enum Country {
BR = "Brazil",
NO = "Norway"
}
Then imagine I have a method that takes a Country
as an argument, like so:
someFunc = (country: Country): void => {
console.log(country) //Will print "Brazil" if country = Country.BR
console.log(Country[country]) //Same as above
console.log(???) //I want to print "BR" if country = Country.BR
}
How do I solve the third console.log
statement?
How do I get a hold of the enum key?
Regards
Enum. GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value. Syntax: public static string GetName (Type enumType, object value);
To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) .
Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
Under the enum constrution you get something like this
Country["BR"] = "Brazil";
Country["NO"] = "Norway";
which is a simple object.
By default you can't get the keys of your enum. But you can iterate over the keys manually and try to find that one.
enum Country {
BR = "Brazil",
NO = "Norway"
}
console.log(Object.keys(Country).find(key => Country[key] === country))
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