是否有一种方法可以获取打字稿中的枚举名称,例如nameof(FirstEnum)
?以下代码在每次定义新的枚举时都必须扩展if开关。有没有更通用的方式可以在打字稿中实现相同的功能?
enum FirstEnum {
First = 0,
Second = 1,
Third = 2,
}
enum SecondEnum {
One,
Two,
}
function translateEnum(type$, val): string {
let lookupKey = '';
if (type$ === FirstEnum) {
lookupKey = `firstenum.${FirstEnum[val]}`;
} else if (type$ === SecondEnum) {
lookupKey = `secondenum.${SecondEnum[val]}`;
} else {
throw new Error('not supported');
}
//lookupkey example: secondenum.One
const result = ''; //translate here, ex. await translationService.translate(lookupkey);
return result;
}
translateEnum(SecondEnum , SecondEnum.One);
答案 0 :(得分:2)
由于将打字稿Enums
转换为JavaScript对象,因此您可以使用in
运算符检查enum
的键值是否是enums
的成员。请注意,这仅适用于非enums
且基于数字的const
。
enum FirstEnum {
First = 0,
Second = 1,
Third = 2,
}
enum SecondEnum {
One,
Two,
}
function translateEnum(val: FirstEnum | SecondEnum): string {
let lookupKey = '';
if (val in FirstEnum || val in SecondEnum) {
console.log(`Enum value ${val} is valid!`);
//lookupkey example: secondenum.One
const result = ''; //translate here, ex. await translationService.translate(lookupkey);
return result;
} else {
console.log(`Enum value ${val} not supported.`);
throw new Error('not supported');
}
}
translateEnum(SecondEnum.One);
translateEnum(10);
Enum value 0 is valid!
Enum value 10 not supported.
Uncaught Error: not supported
at translateEnum (eval at <anonymous> (main-0.js:804), <anonymous>:23:15)
at eval (eval at <anonymous> (main-0.js:804), <anonymous>:27:1)
at main-0.js:804