如何从打字稿中的值获取常量枚举

How to get a const enum from value in typescript

我有两个字符串枚举,我正在尝试通过值将一个转换为另一个。 我要获取的枚举是一个常量字符串枚举。因为它是 const,所以我没有得到它。

即:

const enum MyEnum1 {
     ORANGE = 'orange',
     YELLOW = 'yellow'
}
enum MyEnum2 {
     ORANGE = 'orange',
     BLACK = 'black',
     YELLOW = 'yellow',

}

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

function converter(type2: MyEnum2): MyEnum1 {
     const enumKey = getEnumKeyByEnumValue(MyEnum1, type2);
     if (!enumKey) {
          throw new Error('Key does not exist');
     }
    return MyEnum1[enumKey];
}

您可以在 this link

的 Typescript Playground 中查看此示例

对于转换器函数,我在最后一行遇到错误。我已经尝试过与非 const 枚举相关的方法,它们只适用于非 const 枚举。如果 enum 被定义为 const 则它不起作用。

如何做到?

根据这个答案似乎不可能:

换句话说,这个问题实际上与链接问题中描述的场景相同。

const 枚举在编译期间被完全擦除,这意味着运行时评估是不可能的