Issue
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
Solution
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))
Answered By - Suren Srapyan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.