Reputation: 2187
Enum definition:
enum Colors {
Red = "red",
Blue = "blue"
}
How can I cast some arbitrary sting (e.g. a result from a GET request) to the enum?
const color: Colors = "blue"; // Gives an error
In addition, why do integer enums work but string enums fail to have the same behavior?
enum Colors {
Red = 1,
Blue
}
const color: Colors = 1; // Works
Upvotes: 26
Views: 42461
Reputation: 19729
If you are sure that the strings will always correspond to an item in the enum, it should be alright to cast it:
enum Colors {
Red = "red",
Blue = "blue",
}
const color: Colors = <Colors> "blue";
It won't catch the cases where the string is not valid. You would have to do the check at runtime:
let colorName: string = "blue"; // from somewhere else
let color: Colors;
if (Object.values(Colors).some((col: string) => col === colorName))
color = <Colors> colorName;
else
// throw Exception or set default...
Upvotes: 37