Typescript enums have been a bane of good development in a lot of my cases.
Take the following enum for example:

enum Result {
  Ok,
  Err
}

In reality, the decompiled typescript results in the following:

var Result;
(function (Result) {
  Result[(Result["Ok"] = 0)] = "Ok";
  Result[(Result["Err"] = 1)] = "Err";
})(Result || (Result = {}));

There’s so much weirdness in this.
Let’s try and parse this.

  1. With the var keyword, it attaches a variable called Result to the global scope[^1]
  2. An IIFE is invoked with Result as a paremeter
  3. Result is given the value of Result or {}
  4. Result is given the values of Result["Ok"] = 0, which would give:
[
  {"Ok": 0},
  {"Err": 1}
]

After invoking IIFE, we now are left with the following:

var Result = {}
Result["Ok"] = 0
Result["Err"] = 1

As Result is always given the ++Symbol.Iterator++ type, we can loop over Result like so:

Object.entries(Result)

// Returns…

{
Ok: 0,
0: “Ok”,
Err: 1,
1: “Err”,
}

Like, just why would you do this. You’re just left with a bunch of repeating indexes which are, awkward to navigate when actually using these in code.
It’s why I almost never use them and just use a Dicitionary in code instead, as this allows you to join and implement keys from other dictionaries, extend your types and are generally just far more powerful.

[^1]: The var keyword attaches each variable declared to a global scope, for this reason, it is not recommended


Go back