Amitabh Amitabh - 1 year ago 328
TypeScript Question

How to convert string to enum in TypeScript?

I have defined following enum in TypeScript?

enum Color{
Red, Green

Now In my function I receive color as string. I have tried following code.

var green= "Green";
var color : Color = <Color>green; // Error: can't convert string to enum

How can I convert that value to enum?

Answer Source

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 :