So, are enums ok or not?

I have googled this and even got to the second page, and there does not seem to be any kind of consensus.

As far as I can tell, it’s a bad idea because it creates code you don’t see and accepts inputs that you wouldn’t want. And yet, many people seem to like them more than, say, const unions due to being easier to refactor in bulk.

So what gives? Is this a case of IT people having very strong opinions on stuff that doesn’t matter? Or is there a technical reason for or against it?

Statick,

At work, when I was helping with some frontend stuff, we used object literals.


<span style="color:#323232;">const DIRECTIONS = {
</span><span style="color:#323232;">  UP: "UP",
</span><span style="color:#323232;">  DOWN: "DOWN"
</span><span style="color:#323232;">} as const;
</span><span style="color:#323232;">
</span><span style="color:#323232;">type DIRECTIONS = typeof DIRECTIONS[keyof typeof DIRECTIONS];
</span>

Taken from option 2 in this blog post. …medium.com/alternatives-to-typescript-enums-50e4…___

Fisherswamp,

This is, in my opinion, the absolute best way to do it

fidodo,

That’s what the typescript official docs recommend as an alternative too

www.typescriptlang.org/docs/handbook/enums.html#o…

The const keyword was added after enums. I doubt enums would exist if the feature was added earlier.

Aux,

Use enums when you need enums. Don’t use them when you don’t need them. What’s the issue?

fidodo,

You probably don’t ever need enums since the const keyword was added after enums and const objects handle enum use cases unions don’t.

Aux,

You mean const assertions. Well, the thing is that const assertions are not enums. They don’t handle enum use cases in any way.

fidodo,

I’m talking about if you want an object syntax for accessing constant types to act as an enum www.typescriptlang.org/docs/handbook/enums.html#o…

spartanatreyu,
@spartanatreyu@programming.dev avatar

Basically, you can use them if you want to, but every single case where you would use them would be better served with a union type.

pm_me_your_quackers,

To add, turning everything into an enum can make the code nearly unreadable and hard to work with. This isn’t Rust, and there’s no performance gain for using enums over string unions.

LeafOnTheWind,

Or by an enum class.

fidodo,

Another good option is const objects, it’s a recommended alternative in the official docs. www.typescriptlang.org/docs/handbook/enums.html#o…

bobby_hill,

Yes

  • All
  • Subscribed
  • Moderated
  • Favorites
  • typescript@programming.dev
  • ngwrru68w68
  • rosin
  • GTA5RPClips
  • osvaldo12
  • love
  • Youngstown
  • slotface
  • khanakhh
  • everett
  • kavyap
  • mdbf
  • DreamBathrooms
  • thenastyranch
  • magazineikmin
  • megavids
  • InstantRegret
  • normalnudes
  • tacticalgear
  • cubers
  • ethstaker
  • modclub
  • cisconetworking
  • Durango
  • anitta
  • Leos
  • tester
  • provamag3
  • JUstTest
  • All magazines