Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all values in a string enum?

Tags:

typescript

I have a string enum and need to get all the values. For instance, for the below enum, I'd like to return ["Red", "Yellow"]:

export enum FruitColors {
    Apple = "Red",
    Banana = "Yellow",
}
like image 539
Chris Long Avatar asked Mar 21 '18 21:03

Chris Long


People also ask

Can enum have string values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Can enum be string Java?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)


3 Answers

You're looking for Object.values()

like image 198
SLaks Avatar answered Oct 03 '22 17:10

SLaks


According to this GitHub comment, this can be achieved the following way:

Object.keys(FruitColors).map(c => FruitColors[c]);
like image 40
Chris Long Avatar answered Oct 03 '22 16:10

Chris Long


You can inspect the FruitColors object. Note that if you do not assign names for the enum values, the generated code will be different and a simple key/value based mapping will lead to wrong results. e.g.

export enum FruitColors {
    "Red",
    "Yellow",
}

Object.values(FruitColors); // ["Red", "Yellow", 0, 1]

Because the generated code is along these lines:

var FruitColors;
(function (FruitColors) {
    FruitColors[FruitColors["Red"] = 0] = "Red";
    FruitColors[FruitColors["Yellow"] = 1] = "Yellow";
})(FruitColors = exports.FruitColors || (exports.FruitColors = {}));

You could then just filter the results by typeof value == "string".

like image 24
H.B. Avatar answered Oct 03 '22 17:10

H.B.