我使用typescript声明类型标志的enum如下
export enum OperatorEnum{
None = 0x0,
Equal = 0x1,
NotEqual = 0x2,
GreaterThan = 0x4,
LessThan = 0x10,
GreaterOrEqual = 0x20,
LessOrEqual = 0x40,
Contains = 0x80,
In = 0x100,
}
我收到一个十进制值,比如119。代表119的值是{Equal, NotEqual, GreaterThan, LessThan, GreaterOrEqual, LessOrEqual}
如何使用|从枚举中提取所有值。
TypeScript中的枚举是对象,枚举的键和值都是属性值。在您的示例中,您可以将键与值区分开来,因为您的值是数字。
因此,我们寻找的值是数字,并且具有199 (enumValue & 119
)的位与与不为0:
enum OperatorEnum {
None = 0x0,
Equal = 0x1,
NotEqual = 0x2,
GreaterThan = 0x4,
LessThan = 0x10,
GreaterOrEqual = 0x20,
LessOrEqual = 0x40,
Contains = 0x80,
In = 0x100,
}
const value = 0x77; // 119 in decimal
const matches = Object.values(OperatorEnum)
.filter(v => typeof v === "number" && (value & v) !== 0)
.map(v => OperatorEnum[v as number]); // type guaranteed by `filter`
console.log(matches);
操场上联系