# TypeScript - Numeric Enums

[Last Updated: Oct 14, 2018]

In programming, Enums are set of named identifiers. These identifiers have constant values.

In typeScript enums can be created by using enum keyword. By default enums are assign numeric values starting with 0;

```enum Align{
LEFT, CENTER, RIGHT
}

console.log(Align);```

#### Output

`{ '0': 'LEFT',  '1': 'CENTER',  '2': 'RIGHT',  LEFT: 0,  CENTER: 1,  RIGHT: 2 }`

Compiled JavaScript:

```var Align;
(function (Align) {
Align[Align["LEFT"] = 0] = "LEFT";
Align[Align["CENTER"] = 1] = "CENTER";
Align[Align["RIGHT"] = 2] = "RIGHT";
})(Align || (Align = {}));
console.log(Align);
```

As seen above an enum is compiled to an object with each element assigned to a numeric value starting with zero. At the same time each enum is given string values by their numeric keys (Reverse mappings). That means we can access their numeric values or their string values:

```enum Align {
LEFT, CENTER, RIGHT
}

let a: Align = Align.LEFT;
console.log(a);
let a2: String = Align[0]
console.log(a2);

console.log("-- looping --");
for (let alignKey in Align) {
console.log(`key=\${alignKey}, value=\${Align[alignKey]}`);
}```

#### Output

`0LEFT-- looping --key=0, value=LEFTkey=1, value=CENTERkey=2, value=RIGHTkey=LEFT, value=0key=CENTER, value=1key=RIGHT, value=2`

## Explicit values

As we seen above enums, by default, are started with numeric value of 0. We can also initialize the frist element implicitly. All of the following members will be auto-incremented:

```enum Align {
LEFT = 5, CENTER, RIGHT
}

console.log(Align.LEFT);
console.log(Align.CENTER);
console.log(Align.RIGHT);
console.log("-- looping --");
for (let key in Align) {
console.log(`key=\${key}, value=\${Align[key]}`);
}```

#### Output

`567-- looping --key=5, value=LEFTkey=6, value=CENTERkey=7, value=RIGHTkey=LEFT, value=5key=CENTER, value=6key=RIGHT, value=7`

We can also initialize element other than the first one:

```enum Align {
LEFT, CENTER = 5, RIGHT
}

console.log(Align.LEFT);
console.log(Align.CENTER);
console.log(Align.RIGHT);
console.log("-- looping --");
for (let key in Align) {
console.log(`key=\${key}, value=\${Align[key]}`);
}```

#### Output

`056-- looping --key=0, value=LEFTkey=5, value=CENTERkey=6, value=RIGHTkey=LEFT, value=0key=CENTER, value=5key=RIGHT, value=6`

## Getting all values

Following example shows how to get all enum values:

```enum Align {
LEFT, CENTER, RIGHT
}

//getting all values
let values: Align[] = Object.keys(Align)
.map(key => Align[key])
.filter(value => typeof(value) === "number");
console.log(values);

//getting all string values
let sValues: Align[] = Object.keys(Align)
.map(key => Align[key])
.filter(value => typeof(value) === "string");
console.log(sValues);```

#### Output

`[ 0, 1, 2 ][ 'LEFT', 'CENTER', 'RIGHT' ]`

## Example Project

Dependencies and Technologies Used:

• TypeScript 3.1.1