How to use TypeScript Enum types, especially with Angular 2

Let’s assume you have the following enum in TypeScript:

An enum is just an object. Your enum is written something like this in JavaScript:

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.

Share With Friends:

P.S. Please help me out by checking this offer, then look below for a small Thank You.

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 5, and other fullstack developer goodies.