Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of using ENUM in TypeScript?

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!

like image 764
DongBin Kim Avatar asked Jan 17 '18 07:01

DongBin Kim


1 Answers

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 */ }
like image 181
Lostfields Avatar answered Oct 07 '22 01:10

Lostfields