Amitabh Amitabh - 3 months ago 29
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

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.gitbooks.io/typescript/content/docs/enums.html

Comments