我有以下TypeScript枚举:
enum Country {
BR = "Brazil",
NO = "Norway"
}
然后想象我有一个方法,它将Country
作为参数,如下所示:
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
}
如何解决第三个console.log
声明?
如何获取枚举密钥?
此致
答案 0 :(得分:8)
在enum构造下你得到类似这样的东西
Country["BR"] = "Brazil";
Country["NO"] = "Norway";
这是一个简单的对象。
默认情况下,您无法获取枚举的键。但是你可以手动迭代键并尝试找到那个键。
enum Country {
BR = "Brazil",
NO = "Norway"
}
console.log(Object.keys(Country).find(key => Country[key] === country))
答案 1 :(得分:-1)
我经常使用普通的JavaScript对象而不是枚举,并在其键上使用keyof
运算符来确保类型安全:
const CountryMap = {
BR: "Brazil",
NO: "Norway"
};
// equivalent to: type Country = 'BR' | 'NO';
type Country = keyof typeof CountryMap;
const someFunc = (country: Country): void => {
console.log(country);
}