我有一个这样的枚举:
export enum Colors {
RED = "RED COLOR",
BLUE = "BLUE COLOR",
GREEN = "GREEN COLOR"
}
能否让我知道如何通过值获取枚举键?即,我需要传递“蓝色”并获得“蓝色”。
Colors["BLUE COLOR"]
给出错误Element implicitly has an 'any' type because expression of type '"BLUE COLOR"' can't be used to index type 'typeof Colors'. Property 'BLUE COLOR' does not exist on type 'typeof Colors'.
答案 0 :(得分:6)
是的,您得到了正确的错误。在这种情况下,如果要通过enum key
来获得value
,则必须为.ts重新编写枚举:
export enum Colors {
RED = <any>"RED COLOR",
BLUE = <any>"BLUE COLOR",
GREEN = <any>"GREEN COLOR"
}
然后您可以通过以下方式获得:
let enumKey = Colors["BLUE COLOR"];
console.log(enumKey);
另一种方法是循环遍历,这将花费很少,代码也很嘈杂,我不希望这样做。
Update:
对于.tsx,应该是这样。
export enum Colors {
RED = "RED COLOR" as any,
BLUE = "BLUE COLOR" as any,
GREEN = "GREEN COLOR" as any
}
它也应该像上面的方式一样工作。
答案 1 :(得分:5)
我正在使用此功能
export function getEnumKeyByEnumValue(myEnum: any, enumValue: number | string): string {
let keys = Object.keys(myEnum).filter((x) => myEnum[x] == enumValue);
return keys.length > 0 ? keys[0] : '';
}
开玩笑地测试
describe('enum', () => {
enum TestEnumWithNumber {
ZERO
}
enum TestEnumWithString {
ZERO = 'ZERO'
}
it('should return correct key when enum has number values', function() {
const key = getEnumKeyByEnumValue(TestEnumWithNumber, TestEnumWithNumber.ZERO);
expect(key).toBe('ZERO');
});
it('should return correct key when enum has string values', function() {
const key = getEnumKeyByEnumValue(TestEnumWithString, TestEnumWithString.ZERO);
expect(key).toBe('ZERO');
});
it('should return correct key by passing corresponding string value', function() {
const key = getEnumKeyByEnumValue(TestEnumWithString, 'ZERO');
expect(key).toBe('ZERO');
});
});
希望它对某人有帮助
答案 2 :(得分:3)
const findMe = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];
答案 3 :(得分:1)
您可以执行以下操作以获取枚举键:
enum Colors {
RED = "RED COLOR",
BLUE = "BLUE COLOR",
GREEN = "GREEN COLOR"
}
for (let item in Colors) {
if (Colors[item] === "BLUE COLOR") {
alert(item)
}
}
答案 4 :(得分:1)
改进了 getEnumKeyByEnumValue 而不使用 any:
export function getEnumKeyByEnumValue<
TEnumKey extends string,
TEnumVal extends string | number
>(myEnum: { [key in TEnumKey]: TEnumVal }, enumValue: TEnumVal): string {
const keys = (Object.keys(myEnum) as TEnumKey[]).filter(
(x) => myEnum[x] === enumValue,
);
return keys.length > 0 ? keys[0] : '';
}