Advertisement
Advanced TypeScript, Enums

How would you model a set of flags/permissions using a numeric enum with bitwise values, and how do you check if a flag is set?

Short answer

Assign each enum member a distinct power-of-two value so they can be safely combined with the bitwise OR operator into a single number representing multiple flags at once; check whether a specific flag is present using the bitwise AND operator against that flag's value.

Save TypeScript mock interview
Advertisement
AModel answer
Assign each enum member a distinct power-of-two value so they can be safely combined with the bitwise OR operator into a single number representing multiple flags at once; check whether a specific flag is present using the bitwise AND operator against that flag's value.
enum Permission {
  Read = 1 << 0,   // 1
  Write = 1 << 1,  // 2
  Delete = 1 << 2  // 4
}
const userPerms = Permission.Read | Permission.Write; // 3
const canWrite = (userPerms & Permission.Write) !== 0; // true
Real-world example
Representing a user's combined set of permissions (read/write/delete) compactly as a single stored integer.
Likely follow-ups
  • What are the readability trade-offs of bitwise flag enums compared to using an array or Set of permission strings?
Related topics