在 TypeScript 中使用值字符串(反向映射)获取枚举键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54297376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the enum key with the value string (reverse mapping) in TypeScript
提问by miqrc
I have an enum:
我有一个枚举:
export enum ApiMessages {
logged_ok = 'Logged OK',
register_ok = 'Register OK'
}
I have a function with the enum as a parameter:
我有一个以枚举为参数的函数:
export function responseOK(message: ApiMessages, result ?: any): ApiResponse {
return {
"status": "ok",
"code": 200,
"messageId": ApiMessages[message], <-- KO TS7015
"message": message,
"result": result
};
}
I am calling the function like that:
我这样调用函数:
responseOK(ApiMessages.logged_ok, {user: userRes})
I am trying to return the enum key and the enum string value to the response but I get the TS error:
我试图将枚举键和枚举字符串值返回给响应,但出现 TS 错误:
TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
TS7015:元素隐式具有“任何”类型,因为索引表达式不是“数字”类型。
I have strict TypeScript config. Adding suppressImplicitAnyIndexErrors is not an option.
我有严格的 TypeScript 配置。添加suppressImplicitAnyIndexErrors 不是一个选项。
TypeScript version: 2.9.2
打字稿版本:2.9.2
回答by S?ren D. Pt?us
As described in the handbook:
如手册中所述:
Keep in mind that string enum members do not get a reverse mapping generated at all.
请记住,字符串枚举成员根本不会生成反向映射。
That means there is no simple reverse mapping in your case.
这意味着在您的情况下没有简单的反向映射。
Workaround: Getting a reverse mapping for string enum members
解决方法:获取字符串枚举成员的反向映射
To get the key of an enum member by it's value, you have to iterate through the enum keys and compare the associated value with your target value.
要通过其值获取枚举成员的键,您必须遍历枚举键并将关联的值与您的目标值进行比较。
function getEnumKeyByEnumValue(myEnum, enumValue) {
let keys = Object.keys(myEnum).filter(x => myEnum[x] == enumValue);
return keys.length > 0 ? keys[0] : null;
}
Some demo code follows. You can also see it in action on the TypeScript Playground
一些演示代码如下。您还可以在 TypeScript Playground 上看到它的运行情况
enum ApiMessages {
logged_ok = 'Logged OK',
register_ok = 'Register OK'
}
let exampleValue = ApiMessages.logged_ok;
let exampleKey = getEnumKeyByEnumValue(ApiMessages, exampleValue);
alert(`The value '${exampleValue}' has the key '${exampleKey}'`)
function getEnumKeyByEnumValue(myEnum, enumValue) {
let keys = Object.keys(myEnum).filter(x => myEnum[x] == enumValue);
return keys.length > 0 ? keys[0] : null;
}
Adding this into your responseOK()
you end up with:
将此添加到您的responseOK()
最终结果中:
function responseOK(message: ApiMessages, result ?: any) {
return {
"status": "ok",
"code": 200,
"messageId": getEnumKeyByEnumValue(ApiMessages, message),
"message": message,
"result": result
};
}
回答by Troy Weber
You can easily create a map that allows you to get the key from the value without creating a special function for it.
您可以轻松创建一个映射,该映射允许您从值中获取键,而无需为其创建特殊函数。
export enum ApiMessage {
logged_ok = 'Logged OK',
register_ok = 'Register OK'
}
export type ApiMessageKey = keyof typeof ApiMessage;
export const API_MESSAGE_KEYS = new Map<ApiMessage, ApiMessageKey>(
Object.entries(ApiMessage).map(([key, value]:[ApiMessageKey, ApiMessage]) => [value, key])
)
API_MESSAGE_KEYS.get(ApiMessage.logged_ok); // 'logged_ok'