我收到一个数字类型= 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
}

其他回答

export enum YourEnum {
   enum1 = 'enum1',
   enum2 = 'enum2',
   enum3 = 'enum3',
}

const status = 'enumnumnum';

if (!Object.values(YourEnum)?.includes(status)) {
     throw new UnprocessableEntityResponse('Invalid enum val');
}

如果你在那里找不到如何检查联合包含的具体值,有解决方案:

// 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

更新:

我发现,每当我需要检查一个值是否存在于枚举中,我并不真的需要枚举,类型是一个更好的解决方案。所以我原来答案中的enum变成:

export type ValidColors =
  | "red"
  | "orange"
  | "yellow"
  | "green"
  | "blue"
  | "purple";

最初的回答:

为了清晰起见,我喜欢将值分开,并将调用包含在单独的行上。这里有一个例子:

export enum ValidColors {
  Red = "red",
  Orange = "orange",
  Yellow = "yellow",
  Green = "green",
  Blue = "blue",
  Purple = "purple",
}

function isValidColor(color: string): boolean {
  const options: string[] = Object.values(ValidColors);
  return options.includes(color);
}

对于你的问题,有一个非常简单易行的解决方法:

var districtId = 210;

if (DistrictsEnum[districtId] != null) {

// Returns 'undefined' if the districtId not exists in the DistrictsEnum 
    model.handlingDistrictId = districtId;
}

根据sandersn的说法,最好的方法是:

Object.values(MESSAGE_TYPE).includes(type as MESSAGE_TYPE)