If you’re looking to make your TypeScript code more organized, enums are a powerful tool. They group related values together, giving your code bett...
For further actions, you may consider blocking this person and/or reporting abuse
The initializers here are not necessary. We could leave off the initializers entirely.
But of course, you can still use String enums
I prefer using regular objects with "as const" to act like enums as it has more use cases
Great advice, thanks!
Object like
can work the same way as enums.
Could you mention the use cases where this approach is better?
When working with Angular, if you define an
enumto be used as aninputproperty, it willl require you to assign thatenumto a class attribute of the parent component and later use it in thehtmltemplate, else you simply can't us it. An this is just an example.In that case, a map using
as constand alsokeyof typeofwill let you to use the typed string in thehtml.The approach that unify the definition for
enumand let you use it as is, is the following:The real problem is that TypeScript doesn't recognize an
enumas astring, even if theenumvalues are all strings. This aspect ofenummake them "weird" in constrast ofas constobjects.A better explanation: dev.to/muszynov/something-about-ty...
You can change it to:
const enum loadingStateand it will work the same without being smarter givingas constat the end.Forgive my ignorance about enums 🥺, but what would be a real use case instead of Object?
I really like that in your examples the enumeration are named : which makes it so much better to log them (otherwise you get numbers) ☺️
Thank you!
Hope you learned something new from the article 😊
I like these examples. it's easy to catch and memorize.