Reputation: 3074
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",
}
Upvotes: 9
Views: 12762
Reputation: 184947
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"
.
Upvotes: 2
Reputation: 1
Maybe you can try this function, it can return all values in string + number enum type, not only string Enum
const getAllValuesEnum = (enumType: any) => {
const keysAndValues = Object.values(enumType);
const values = [];
keysAndValues.forEach((keyOrValue: any) => {
if (isNaN(Number(keyOrValue))) {
values.push(enumType[keyOrValue] || keyOrValue);
}
});
return values;
};
Example:
enum MyEnum {
A = "a",
B = 7,
C = "c",
D = 1,
}
It will return [ 1, 7, 'a', 'c' ]
Upvotes: -1
Reputation: 3074
According to this GitHub comment, this can be achieved the following way:
Object.keys(FruitColors).map(c => FruitColors[c]);
Upvotes: 1