我有一个二进制字符串,我想将其转换为等效的标志枚举值。我的尝试:
const permissionNum = parseInt(this.auth.decodedToken.permissions, 2);
const userPermissions: PermissionFlags = PermissionFlags[PermissionFlags[permissionNum]];
这是枚举:
export enum PermissionFlags {
None = 0,
RemoveMember = 1 << 0,
Invite = 1 << 1,
EditArticleSettings = 1 << 2,
CheckOut = 1 << 3,
CheckIn = 1 << 4,
CanView = 1 << 5,
IsOwner = 1 << 6,
xxx = 1 << 7
}
只要它是单个标志,它就可以工作。因此,如果字符串为00111000
,则将其解析为56,但userPermissions
保持未定义状态。在Typescript中不可能吗?
TypeScript中的枚举与C#中的枚举相比有所不同。毕竟,它们会被编译成一个简单的JavaScript对象,并根据名称和值建立索引。因此,该对象将不包含作为多个标志组合的索引的有效条目,而仅包含单个标志值。
例如,您的枚举声明将编译为以下JavaScript:
export var PermissionFlags;
(function (PermissionFlags) {
PermissionFlags[PermissionFlags["None"] = 0] = "None";
PermissionFlags[PermissionFlags["RemoveMember"] = 1] = "RemoveMember";
PermissionFlags[PermissionFlags["Invite"] = 2] = "Invite";
PermissionFlags[PermissionFlags["EditArticleSettings"] = 4] = "EditArticleSettings";
PermissionFlags[PermissionFlags["CheckOut"] = 8] = "CheckOut";
PermissionFlags[PermissionFlags["CheckIn"] = 16] = "CheckIn";
PermissionFlags[PermissionFlags["CanView"] = 32] = "CanView";
PermissionFlags[PermissionFlags["IsOwner"] = 64] = "IsOwner";
PermissionFlags[PermissionFlags["xxx"] = 128] = "xxx";
})(PermissionFlags || (PermissionFlags = {}));
如果现在使用索引56索引到PermissionFlags
对象中,则会得到undefined
,因为没有为该特定索引定义任何值。
我希望在以下代码段中使用该方法:
export enum PermissionFlags {
None = 0,
RemoveMember = 1 << 0,
Invite = 1 << 1,
EditArticleSettings = 1 << 2,
CheckOut = 1 << 3,
CheckIn = 1 << 4,
CanView = 1 << 5,
IsOwner = 1 << 6,
xxx = 1 << 7
}
export function hasPermission(userPermissions: number | string, flags: PermissionFlags): boolean {
const perm = typeof userPermissions === "number" ? userPermissions : parseInt(userPermissions, 2);
return (perm & flags) !== 0;
}
// Check for permissions by specifying the user permission mask and the target permission flags
const canInvite = hasPermission("00111000", PermissionFlags.Invite);
const canCheckInAndIsOwner = hasPermission(32, PermissionFlags.CheckIn | PermissionFlags.IsOwner);
const canCheckOut = hasPermission(PermissionFlags.CheckOut | PermissionFlags.IsOwner, PermissionFlags.CheckOut);