I\'m learning TypeScript using this ebook as a reference. I\'ve checked the TypeScript Official Documentation but I don\'t find information about enum flags.
The official documentation has this example that I will add some details that are crucial to use enum and flags.
enum FileAccess {
None,
Read = 1 << 1,
Write = 1 << 2,
}
In TypeScript, you can assign a value directly with =
let x:FileAccess = FileAccess.Read;
But this might override previous values. To get around that you can use |=
to append a flag.
x |= FileAccess.Write;
At this point, the variable x
is Read and Write. You can remove a value by using the ampersand and tilde:
x &= ~FileAccess.Read;
Finally, you can compare to see if one of the value is set to the variable. The accepted answer is not right. It should not just use the ampersand symbol but also check with ===
to the desired value. The reason is the ampersand returns a number, not a boolean.
console.log(FileAccess.Write === (x & FileAccess.Write)); // Return true
console.log(FileAccess.Read === (x & FileAccess.Read)); // Return false