DEV Community

Discussion on: State Management: How to tell a bad boolean from a good boolean

Collapse
 
ahyagoub40 profile image
Ahmed Yagoub

Interesting article. Would love to see how the enum is defined and used in JavaScript too : )

Collapse
 
mattpocockuk profile image
Matt Pocock

Added as an addendum :)

Collapse
 
mdledoux profile image
Martin Ledoux

Ahmed,
This looks like a good and simple approach to achieving Enum in JS:

tutorialspoint.com/what-is-the-syn...

Note

Be sure to use Object.freeze(), as objects (and Arrays) can still have their properties/elements modified, even when declared as const.

Observation

Even in the author's post using TypeScript, Matt technically did not use an Enum construct, but rather he simulated Enum by defining a new Type. Enum is actually supported in TypeScript: typescriptlang.org/docs/handbook/e...

I'm not sure why he did this instead of defining an actual Enum, but it certainly seems to achieve the same end result. With that said, it sounds like you probably do not use TypeScript, so this observation is probably not very relevant for you.

Collapse
 
mattpocockuk profile image
Matt Pocock

Hello! I find having strings defined like this makes for a better TS experience and easier debugging. It also makes the article easier to read for non-TS users.

Thread Thread
 
randomuser profile image
polyrytm • Edited

I get what you are saying, and i always opt for the way you did it here, but they are not enums. The approach is the same, but I don't really see why you would want to name them incorrectly. If readers want to find out more and search for 'typescript enums' they will see different things than you show here.

You are using a union of string literals.
typescriptlang.org/docs/handbook/2...

Thread Thread
 
mattpocockuk profile image
Matt Pocock • Edited

Even though I haven't used the Typescript 'enum' constructor, what I've shown above is an enumerated set of values - an enum. I've used the above syntax because it's more common to declare enumerated events/messages/actions using union types than TS enums.

Thread Thread
 
randomuser profile image
polyrytm

Saying you're using a feature in typescript called enums will have interested people searching for 'typescript enums'. They will end up on a long 'typescript enums' page in the TS manual which is about 'typescript enums'... and none of it is about what you use here.

But more confusement is better i guess :)

Thread Thread
 
mattpocockuk profile image
Matt Pocock

For those reading this thread, TS enums can achieve exactly the same behaviour as I described above.

Collapse
 
ahyagoub40 profile image
Ahmed Yagoub

Yeah, I don’t use TS and haven’t learned yet. Thanks for this