在 TypeScript 中使用值字符串(反向映射)获取枚举键 [英] Getting the enum key with the value string (reverse mapping) in TypeScript

查看:195
本文介绍了在 TypeScript 中使用值字符串(反向映射)获取枚举键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举:

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
    };
}

我是这样调用函数的:

responseOK(ApiMessages.logged_ok, {user: userRes})

我正在尝试将枚举键和枚举字符串值返回给响应,但出现 TS 错误:

I am trying to return the enum key and the enum string value to the response but I get the TS error:

TS7015:元素隐式具有any"类型,因为索引表达式不是number"类型.

TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.

我有严格的 TypeScript 配置.添加suppressImplicitAnyIndexErrors 不是一个选项.

I have strict TypeScript config. Adding suppressImplicitAnyIndexErrors is not an option.

TypeScript 版本:2.9.2

推荐答案

手册:

请记住,字符串枚举成员根本不会生成反向映射.

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.

要通过枚举成员的值获取其键,您必须遍历枚举键并将关联的值与目标值进行比较.

To get the key of an enum member by its 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;
}

您可以按如下方式更严格地键入(请注意,我们可以将 enum 解释为可索引类型,此处的键和值都是字符串):

You can type this more strictly as follows (note that we can interpret our enum as an indexable type with key and value both being strings here):

function getEnumKeyByEnumValue<T extends {[index:string]:string}>(myEnum:T, enumValue:string):keyof T|null {
    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

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<T extends {[index:string]:string}>(myEnum:T, enumValue:string):keyof T|null {
    let keys = Object.keys(myEnum).filter(x => myEnum[x] == enumValue);
    return keys.length > 0 ? keys[0] : null;
}

将其添加到您的 responseOK() 中,您会得到:

Adding this into your responseOK() you end up with:

function responseOK(message: ApiMessages, result ?: any) {
    return {
        "status": "ok",
        "code": 200,
        "messageId": getEnumKeyByEnumValue(ApiMessages, message),
        "message": message,
        "result": result
    };
}

这篇关于在 TypeScript 中使用值字符串(反向映射)获取枚举键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆