从实例中获取TypeScript枚举名称

时间:2018-01-16 07:35:03

标签: javascript reactjs typescript enums

我有以下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声明?

如何获取枚举密钥?

此致

2 个答案:

答案 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);
}