Expanding on the response provided by @Esqarrouth, it is important to note that in an enum, each value except for string enums will result in two keys being generated. For instance, consider the following enum defined in TypeScript:
enum MyEnum {
a = 0,
b = 1.5,
c = "oooo",
d = 2,
e = "baaaabb"
}
Upon transpilation into Javascript, the resulting code will look like this:
var MyEnum;
(function (MyEnum) {
MyEnum[MyEnum["a"] = 0] = "a";
MyEnum[MyEnum["b"] = 1.5] = "b";
MyEnum["c"] = "oooo";
MyEnum[MyEnum["d"] = 2] = "d";
MyEnum["e"] = "baaaabb";
})(MyEnum || (MyEnum = {}));
In the above example, you can observe that having an entry like a
assigned the value 0
results in two corresponding keys; MyEnum["a"]
and MyEnum[0]
. Conversely, string values such as entries c
and e
only generate one key.
To determine the total count of keys, one can identify the Keys that are not numeric, thus:
var MyEnumCount = Object.keys(MyEnum).map((val, idx) => Number(isNaN(Number(val)))).reduce((a, b) => a + b, 0);
This code snippet iterates over all keys, assigning a value of 1
to string keys and 0
to numerical keys, then aggregates them using the reduce function.
An alternative method that may be easier to comprehend is as follows:
var MyEnumCount = (() => {
let count = 0;
Object.keys(MyEnum).forEach((val, idx) => {
if (Number(isNaN(Number(val)))) {
count++;
}
});
return count;
})();
You can experiment with this concept on the TypeScript playground available at https://www.typescriptlang.org/play/