Determine the number of enum elements TypeScript
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)
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 two 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;
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)
})