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.
- With the
varkeyword, it attaches a variable calledResultto the global scope[1] - An IIFE is invoked with
Resultas a paremeter Resultis given the value ofResultor{}Resultis given the values ofResult["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.
Backlinks
No backlinks found.
Go back