I have defined the following enum in TypeScript:
enum Color{ Red, Green }
Now in my function I receive color as a string. I have tried the following code:
var green= "Green"; var color : Color = <Color>green; // Error: can't convert string to enum
How can I convert that value to an enum?
Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.
Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
An enum is usually selected specifically because it is immutable - i.e. you would never want the values to change as it would make your application unpredictable.
Enums in TypeScript 0.9 are string+number based. You should not need type assertion for simple conversions:
enum Color{ Red, Green } // To String var green: string = Color[Color.Green]; // To Enum / number var color : Color = Color[green];
Try it online
I have documention about this and other Enum patterns in my OSS book : https://basarat.gitbook.io/typescript/type-system/enums
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