To further expand on @Esqarrouth's answer, each value in an enum will produce two keys, except for string enum values. For example, given the following enum in TypeScript:
enum MyEnum {
a = 0,
b = 1.5,
c = "oooo",
d = 2,
e = "baaaabb"
}
After transpiling into Javascript, you will end up with:
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 = {}));
As you can see, if we simply had an enum with an entry of a
given a value of 0
, you end up with two keys; MyEnum["a"]
and MyEnum[0]
. String values on the other hand, simply produce one key, as seen with entries c
and e
above.
Therefore, you can determine the actual count by determining how many Keys are not numbers; ie,
var MyEnumCount = Object.keys(MyEnum).map((val, idx) => Number(isNaN(Number(val)))).reduce((a, b) => a + b, 0);
It simply maps through all keys, returning 1
if the key is a string, 0
otherwise, and then adds them using the reduce function.
Or, a slightly more easier to understand method:
var MyEnumCount = (() => {
let count = 0;
Object.keys(MyEnum).forEach((val, idx) => {
if (Number(isNaN(Number(val)))) {
count++;
}
});
return count;
})();
You can test for yourself on the TypeScript playground https://www.typescriptlang.org/play/