Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string to enum in TypeScript?

Tags:

typescript

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?

like image 398
Amitabh Avatar asked Jun 29 '13 13:06

Amitabh


People also ask

How do I convert string to 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.

What is enum in TypeScript with example?

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.

Does TypeScript support enum?

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.

Can we change enum values in TypeScript?

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.


1 Answers

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

like image 52
basarat Avatar answered Oct 09 '22 10:10

basarat