Javascript does not have a proper (static) enum
type, but you can achieve something very close using the same code Typescript generates for its enums.
To offer enums but still be valid JS, you want an object where each enum element (name) is a key, mapping to a unique value (typically an int, since most languages with enums back them with integer values).
For an enum like enum Color {Red, Green, Blue};
, you would end up with code containing:
Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue";
This creates an object with a key for each enum element's name, and for each element's value. The final object looks like:
var Color; (function(Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue"; })(Color || (Color = {})); document.getElementById("result").textContent = JSON.stringify(Color);
<pre id="result"></pre>
This allows you to access the enum values using the traditional Color.Red
syntax, but also allows you to map values back into names using Color[Color.Red]
(or a variable containing one of the enum values).
For example:
var Color; (function(Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Blue"] = 2] = "Blue"; })(Color || (Color = {})); document.getElementById("red").textContent = Color.Red; // Should print "0" var currentColor = Color.Green; document.getElementById("green").textContent = Color[currentColor]; // Should print "Green" currentColor = Color.Blue; document.getElementById("blue").textContent = Color[currentColor]; // Should now print "Blue"
<pre id="red"></pre> <pre id="green"></pre> <pre id="blue"></pre>