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
To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.
Using string-based enums in C# is not supported and throws a compiler error. Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string.
Enum's in . Net are integral types and therefore any valid integral value can be cast to an Enum type. This is still possible even when the value being cast is outside of the values defined for the given enumeration!
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With