Enum Count/Values

Topics: General, Language Specification
Jan 23, 2014 at 8:44 PM
Are there functions to query an enum definition for the number of elements defined?

Also, to retrieve their text based on values or get an array of the values as strings?

I know this is possible in C#, but I haven't found anything yet about doing something like this in TypeScript. I'd like to be able to get an Enum value at random for a function or be able to list them in a drop-down for some tests I'm doing.

Thanks!
Developer
Jan 23, 2014 at 11:27 PM
There are no specific reflection capabilities in TypeScript like C#. That said, an enum is just an object with some properties which you could loop through and process accordingly.
enum E {
    A,
    B
}

for(var e in E) { 
    console.log(e); 
}
will print 0,1,A,B. The enum object has a reverse mapping so you can index into it by A to find that its value is 0, and index via 0 and find that that value corresponds to A. Assuming your enum values are not crazy (like naming some members with numbers and some with words) you should be able to use this to get at the patterns you want.
Jan 27, 2014 at 8:22 PM
Edited Jan 27, 2014 at 10:08 PM
Thanks Dan,

This is what I ended up doing in the end for anyone interested:
    var n: number = Object.keys(MyEnum).length / 2;

    return MyEnum[getRandomInt(0, n - 1)];
However, I couldn't cast the result back to my enum type from the string (at least not explicitly). Haven't seen how it reacts when it occurs during runtime.
Jan 27, 2014 at 10:11 PM
Looks like the string won't compare with the enum, it just skips over it in my switch case.

So, currently, I'm taking the result of that function above (a string) and passing it to a function which takes a value of my enum as a parameter. It's not complaining during compile time if I have my function return an 'any' (though it does if I use my enum).

But it's still a string at runtime and the switch I have to check the enum just skips over it.

It looks like the TypeScript generates the select with the number. So, I guess I should just have my function return the random number instead of the text? It'd be nice to be able to maintain the sanctity of the enum throughout.