获取所有值代表标志枚举中的十进制值
Get all values represent decimal value in flag 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);
我正在使用打字稿来声明类型标志的枚举,如下所示
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);