我想从字符串枚举中获取密钥作为字符串。
enum myEnum {
myFoo = "My Foo",
myBar = "My Bar",
}
然后我需要从'myFoo'
获得myEnum.myFoo
我已经解决了这个问题,但似乎可以更简单
function getKeyOfMyEnum(myVal: string): string {
for (var enm in myEnum) {
if (isValid(enm) && myEnum[enm] === myVal)
return enm;
}
return '' //I need the type not to be undefined
function isValid(value: string): value is keyof typeof myEnum {
return value in myEnum;
}
}
然后
string str = getKeyOfMyEnum(myEnum.myFoo ) //str ==='myFoo'