TypeScript: Enums

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 {

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)


Share on facebook
Share on twitter
Share on pinterest
Share on linkedin

Table of Contents

Postagens Relacionadas


Chanson douce

Chanson douce () – Drama, Crime – 1h 40min –   Nota: 6/10   Sinopse     Elenco Leïla Bekhti Como – Myriam Karin Viard

Outpost 2: Inferno Negro

O ano é 1945, 2ª Guerra Mundial, e um cientista alemão de nome Klausener está trabalhando em uma tecnologia nova e assustadora que tem o poder de criar um ex…


Atrevimiento () – Mistério – 0h 0min –   Nota: 7/10   Sinopse     Elenco Tomás Becerra Como – Ángel Romero Flores Como –