I've been digging in enum
in TypeScript and it got me thinking what's the point of using it. I'm not questioning the value of it. It's just that I'm unfamiliar with the usage of it and which has been leading me to code like declaring some sort of a bunch of objects which keeps constants used throughout the application without using enum
. To sum up, what's the point of using it and difference than just using/declaring manual objects which keeps some constants? Any insight would be appreciated!
Enums is handy to force type validations (not easy with constants) and it's easy to convert a readable enum to a number and vice a versa.
enum Access {
Read = 1,
Write = 2,
Execute = 4,
AnotherAccess = 8
}
I use it all the time when I have a set of choices, to make it clear what kind of values the code accept and for code readability
if( myAccess == Access[Access[myaccess]] ) // enum used
Bitwise operations is another thing, eg, my accesses is (Access.Read | Access.Execute)
var myAccess = Access.Read | Access.Execute; //instead of 1 | 4 = 5
// do I have write access?
if ( (myAccess & Access.Write) > 0) { /* yes */ }
// do I have read and execute
if ( (myAccess & (Access.Read | Access.Execute)) > 0) { /* yes */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With