我收到一个数字类型= 3,必须检查它是否存在于这个enum:
export const MESSAGE_TYPE = {
INFO: 1,
SUCCESS: 2,
WARNING: 3,
ERROR: 4,
};
我发现最好的方法是将所有Enum值作为一个数组,并在其上使用indexOf。但结果代码不是很容易读懂:
if( -1 < _.values( MESSAGE_TYPE ).indexOf( _.toInteger( type ) ) ) {
// do stuff ...
}
有更简单的方法吗?
这只适用于非const,基于数字的枚举。有关const enum或其他类型的enum,请参见此答案
如果你使用的是TypeScript,你可以使用一个实际的enum。然后你可以用in检查它。
export enum MESSAGE_TYPE {
INFO = 1,
SUCCESS = 2,
WARNING = 3,
ERROR = 4,
};
var type = 3;
if (type in MESSAGE_TYPE) {
}
这是因为当你编译上面的枚举时,它会生成下面的对象:
{
'1': 'INFO',
'2': 'SUCCESS',
'3': 'WARNING',
'4': 'ERROR',
INFO: 1,
SUCCESS: 2,
WARNING: 3,
ERROR: 4
}
如果你想让它与字符串ENUM一起工作,你需要使用Object.values(ENUM).includes(enumenumvalue),因为字符串ENUM不是反向映射的,根据https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html:
enum Vehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}
就变成:
{
Car: 'car',
Bike: 'bike',
Truck: 'truck'
}
所以你只需要做:
if (Object.values(Vehicle).includes('car')) {
// Do stuff here
}
如果你得到一个错误:属性“values”在类型“ObjectConstructor”上不存在,那么你不是针对ES2017。您可以使用这个tsconfig。json配置:
"compilerOptions": {
"lib": ["es2017"]
}
或者你可以做任意类型的转换:
if ((<any>Object).values(Vehicle).includes('car')) {
// Do stuff here
}
enum ServicePlatform {
UPLAY = "uplay",
PSN = "psn",
XBL = "xbl"
}
就变成:
{ UPLAY: 'uplay', PSN: 'psn', XBL: 'xbl' }
so
ServicePlatform.UPLAY in ServicePlatform // false
解决方案:
ServicePlatform.UPLAY.toUpperCase() in ServicePlatform // true
如果你在那里找不到如何检查联合包含的具体值,有解决方案:
// source enum type
export const EMessagaType = {
Info,
Success,
Warning,
Error,
};
//check helper
const isUnionHasValue = <T extends number>(union: T, value: T) =>
(union & value) === value;
//tests
console.log(
isUnionHasValue(EMessagaType.Info | EMessagaType.Success),
EMessagaType.Success);
//output: true
console.log(
isUnionHasValue(EMessagaType.Info | EMessagaType.Success),
EMessagaType.Error);
//output: false