Let’s assume you have the following enum in TypeScript:
The benefit from typing is very limited in enums. Let me explain…
A very common thing you might want to do, is convert a string to an enum. This line is valid:
But it’s not useful, because
So, you should always store your values as numbers, which you can obtain as follows:
How do you convert a string to an enum in TypeScript?
This makes the previous comparison work:
Now, a couple questions remain:
How to convert a TypeScript enum value to a string?
How to get all the values of a TypeScript enum type?
Gotcha: Undefined enum type in Angular 2 views
If you write this in your Angular2 template:
It will fail, because it doesn’t have access to imported types (it gets executed later by AngularJS).
To make it work, your component will need to have a reference to the enum type / object, something like:
Runnable Demo With All Solutions
Here is an example that explains everything I pointed in here:
(Click the ▶ button at the top right to see it in action)
This post was inspired by this StackOverflow answer.
How did I learn that?
As a bonus for coming here, I'm giving away a free newsletter for web developers that you can sign up for from here.
It's not an anything-and-everything link list. It's thoughtfully collected picks of articles and tools, that focus on Angular 2+, ASP.NET (4.x/MVC5 and Core), and other fullstack developer goodies.
Take it for a test ride, and you may unsubscribe any time.
You might also want to support me by checking these out [Thanks]: