Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the number of enum elements TypeScript

People also ask

How do you count enums?

You can use Enum. GetNames to return an IEnumerable of values in your enum and then. Count the resulting IEnumerable.

Can you have a list of enums?

In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet . The order of the new list will be in the iterator order of the EnumSet . The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum.

What is Enumtype?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.


Typescript does not provide a standard method to get the number of enum elements. But given the the implementation of enum reverse mapping, the following works:

Object.keys(ExampleEnum).length / 2

Note, for string enums you do not divide by zero as no reverse mapping properties are generated:

Object.keys(StringEnum).length;

Enums with mixed strings and numeric values can be calculated by:

Object.keys(ExampleEnum).filter(isNaN).length

If you have an enum with numbers that counts from 0, you can insert a placeholder for the size as last element, like so:

enum ERROR {
  UNKNOWN = 0,
  INVALID_TYPE,
  BAD_ADDRESS,
  ...,
  __LENGTH
}

Then using ERROR.__LENGTH will be the size of the enum, no matter how many elements you insert.

For an arbitrary offset, you can keep track of it:

enum ERROR {
  __START = 7,
  INVALID_TYPE,
  BAD_ADDRESS,
  __LENGTH
}

in which case the amount of meaningful errors would be ERROR.__LENGTH - (ERROR.__START + 1)


The accepted answer doesn't work in any enum versions that have a value attached to them. It only works with the most basic enums. Here is my version that works in all types:

export function enumElementCount(enumName: any): number {
    let count = 0
    for(let item in enumName) {
        if(isNaN(Number(item))) count++
    }
    return count
}

Here is test code for mocha:

it('enumElementCounts', function() {
    enum IntEnum { one, two }
    enum StringEnum { one = 'oneman', two = 'twoman', three = 'threeman' }
    enum NumberEnum { lol = 3, mom = 4, kok = 5, pop = 6 }
    expect(enumElementCount(IntEnum)).to.equal(2)
    expect(enumElementCount(StringEnum)).to.equal(3)
    expect(enumElementCount(NumberEnum)).to.equal(4)
})

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/