Ole
Ole

Reputation: 46940

Using integers as values with a Typescript Enum?

When using integers as values in a Typescript enum it seems they all turn in to keys. Here's an example:


enum Precision {
  ONE = 1,
  TWO = 2
}

const keys = Object.keys(Precision)
console.log(keys) //["1", "2", "ONE", "TWO"]

Also if we try to get the values like this:

let v:number[] = Object.keys(Precision).map(key => Precision[key])

console.log(v)  //["ONE", "TWO", 1, 2]

Is this a bug? Is it possible to use integer values and get the expected semantics? When using string values the above examples turn out OK. Here's a complete demo:

https://stackblitz.com/edit/typescript-enum-values

Upvotes: 2

Views: 5243

Answers (1)

adiga
adiga

Reputation: 35222

This is how enum works in typescript. It creates an object which will map the string keys to numbers and numbers back to those keys (Documentation)

Reverse mappings

In addition to creating an object with property names for members, numeric enums members also get a reverse mapping from enum values to enum names.

This how the enum is transpiled to javascript (Typescript playground)

var Precision;
(function (Precision) {
    Precision[Precision["ONE"] = 1] = "ONE";
    Precision[Precision["TWO"] = 2] = "TWO";
})(Precision || (Precision = {}));

That is a fancy way of writing:

var Precision = {}

Precision["ONE"] = 1
Precision["TWO"] = 2

Precision[1] = "ONE"
Precision[2] = "TWO"

This makes it easy for you to convert the string value to number and numeric value to string using the bracket notation.

Do note that only numeric enum values get this Reverse mapping. If you create

enum Precision {
  ONE = "1 value",
  TWO = 2
}

It gets converted to:

var Precision = {};

Precision["ONE"] = "1 value"
Precision["TWO"] = 2

Precision[2] = "TWO";

without the "1 value" key in the object

Upvotes: 4

Related Questions