Check out our Angular Book Series.

String Enums in TypeScript - Part 4

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 fourth part of that series. Check out part 1, part 2, and Part 3. This article will focus on creating String based Enums.

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 or string 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 String based Enum

It is interesting that Enum's can be used to represent textual values too. Look at this:

enum MyColors {
Blue = "#0000FF",
Red = "#FF0000",
Green = "#00FF00",

The value of the color name represents the hex value of the actual color. I recently could have used something similar when dynamically applying colors to the header of a site based on which section the user was viewing. Get the individual colors, and output them:

let myColor1 :MyColors = MyColors.Blue;
let myColor2 :MyColors = MyColors.Red;
let myColor3 :MyColors = MyColors.Green;


You'll see something like this:

Enums are an interesting data type, caught somewhere between an array and a class.

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