Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cast a string to an enum in Typescript

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
like image 318
Dylan Kerler Avatar asked Jul 09 '20 18:07

Dylan Kerler


People also ask

Can you cast a string to an enum?

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.

Can we give string value in enum?

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.

Can you cast int to enum?

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!


1 Answers

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...
like image 142
JCOC611 Avatar answered Oct 11 '22 07:10

JCOC611