Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  153] [ 6]  / answers: 1 / hits: 16835  / 6 Years ago, tue, january 16, 2018, 12:00:00

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


More From » reactjs

 Answers
41

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))

[#55451] Friday, January 12, 2018, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adam

Total Points: 363
Total Questions: 102
Total Answers: 104

Location: Burkina Faso
Member since Thu, Dec 15, 2022
1 Year ago
;