TypeScript: Enums

Thiago S. Adriano
TypeScript Brasil
Published in
2 min readFeb 26, 2018

In this article I’ll show how we can work with Enums in TypeScripy. Enums allow us to define a set of named constants. Who works with languages like C#, Java … etc Enums isn’t a new feature, but if it is your first contact with Enum, I’ll show some examples with TypeScript using enums.

Numeric enums

I’ll start off with numeric. Below we have a numeric enum where Monday is initialized with 1, all the others are follow the sequence 1… 2… 3… etc until 7 when end a week.

export enum Day {
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}

Now, to work with our enum Day, we can use a number or index. Below, we have some examples show how we can work with our enum:

var day = Day[1]; // Monday
var dayNumber: string = Day[day]; // 1
var dayfromString = Day["Monday"]; // 1
console.log(this.EnumStringVal(day, Day)); // Monday
console.log(this.EnumStringVal(dayNumber, Day)); // Monda

To list a enum, we can use a for. Below we can see a example with a loop.

for (var prop in Day) {
if (Day.hasOwnProperty(prop) &&
(isNaN(parseInt(prop)))) {
console.log("dia: " + prop);
}
}

You can see this result below:

Now, If we wanted, we could leave off the initializers entirely:

export enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}

Here, Moday would have the value 0, Tuesday would have 1 … etc. It works because TypeScript has a auto-incrementing behavior.

To finish, let’s to go to see a simple of TypeScript using Enum taken from TypeScriptlang.org

enum Response {
No = 0,
Yes = 1,
}
function respond(recipient: string, message: Response): void {
// ...
}
respond("Princess Caroline", Response.Yes)

--

--