Check out our Angular Book Series.

Enums in TypeScript - Part 3

I'm writing a longer series of articles about Typescript. This will be extra material to support my upcoming Angular 4 book. This is the third part of that series. Check out part 1 and part 2. This article will focus on Enums, a TypeScript data type that does not exist in JavaScript.

What is an Enum?

Enums are a data type I have not come across in most other languages, but they are inspired by C#. An enum is a way to give friendly names to numerical values. They are like an array with indexes, but more specific. I can envision using something like this with a view stack style component and using an enum to handle which view is currently displayed. Or, I might use it with an event class instance to determine what type of event occurred. Or it could be used to determine what color style to apply to certain text.

Create a Number based Enum

I'm going to start by creating a simple sample with a number based enum:


enum MyNumbers {
First,
Second,
Third
}

The MyNumbers enum contains four values each one representing a number. Since enums are sort of like arrays, the First item is at the 0 index, the second item will have the value of 1, and so on. We can use MyNumbers like it was it's own variable type:


let myNum :MyNumbers = MyNumbers.First;

Output this value.


console.log(myNum);

What do you think you'll get? Since it is the value of MyNumbers.First and that is the first element of the zero-based index, you'll get number 0:

A benefit of enums is that we can control the number scheme:


enum MyNumbers {
First = 1,
Second,
Third
}

We specified the First item is equal to the number 1. Turn each element into a variable:


let myNum1 :MyNumbers = MyNumbers.First;
let myNum2 :MyNumbers = MyNumbers.Second;
let myNum3 :MyNumbers = MyNumbers.Third;

Then output them:


console.log(myNum1);
console.log(myNum2);
console.log(myNum3);

You'll see:

Now our text numbers match up with the actual text index. We can control the numbers even if they aren't in sequential order. Add a new entry to the MyNumbers enum:


enum MyNumbers {
First = 1,
Second,
Third,
Ten = 10,
}

This is number 10, skipping four through 9. Grab it as a variable and output it:


let myNum10 :MyNumbers = MyNumbers.Ten;
console.log(myNum10);

Combined with our other outputs, you'll see something like this:

Enums provide a lot of flexibility.

Enums can also be created to use a string based index, and we'll discuss that in the next article.

Keep up to date by reading DotComIt's Monthly Technical Newsletter

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.