In this article, you'll learn about what enums are and how you can use them in your projects. Enums, short for Enumerated Types.
This is going to...
For further actions, you may consider blocking this person and/or reporting abuse
Nice article bro 🔥🔥
Could you give me an example of when I could use an enum instead of an object, please?
Keep going on the series dude!
Objects are re-assignable but you can't assign values to enums types.
But if we use object that it will allows us:
You can check the playground:
typescriptlang.org/play?#code/PTAE...
Thanks bro! 🤝
by appending
as const
to the value ofobj
you even get a read-only version of it, which can not be modified at runtime, and whereobj.no
andobj.yes
have a narrowed type of the string literal value!To even get a type for all the possible values, you can use the following snippet:
of course it might help to have the same casing for both keys and values to simplify your searches.
Putting it all together:
(yes, you can export a type and a value with the same name from a module!)
This still allows you to use literal values everywhere and from what I know if as close as you can get to an enum.
If you need to reference the type of one of the keys from the const, you need to use
typeof YesNo.Yes
. (There are other options but they are longer.)Hope it helps
Thanks mate! It will helps for sure, I was searching for that way of typing
🤝🤝
Helping a lot! 🫀
Please keep continuing the series mate!
Thank you! 🔥🔥
Thanks mate. Definitely.
Really cool and helpful! Thanks!
I am glad you find it useful 😊
Great breakdown :) and thank you for sharing that the Heterogeneous enums are a bad idea! Keep up the good work!
Thanks mate 😊
I loved this post series; it's incredible!
Thanks Heather.
Since I discovered you can use strings as types I just use the following:
I find it actually less confusing than enums?
I wish this article didn't get this much positive feedback - or any at all for that matter.
I see comments like "Really cool and helpful! Thanks!". No, it's the opposite of helpful. It's spreading an anti-pattern. Nothing wrong with talking about what Enums are. But if you do that, you should also talk whether Enums should ever be used in TS. And the answer is - in most cases they should not.
TypeScript Enums are an awkward attempt to make Enums from C# or Java work in JS. They have weird edge-cases and should almost never be used. String literals will achieve the result with better ergonomics in most situations. This is the most important thing anybody need to know about JS Enums.
Don't believe me? Just do a quick google search and see smarter people talk about it.
I can just agree. Enums in TypeScript should be avoided. See also @karfau answer for a better approach.
Great article..
Such a great series of articles. Although I used type script in some of my projects, it helps me simplify, popularize, and understand better some subtleties.
Great job man! Appreciate 🔥