HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCritical

How do I convert a string to enum in TypeScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
enumtypescripthowconvertstring

Problem

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 = green; // Error: can't convert string to enum


How can I convert that value to an enum?

Solution

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 documentation about this and other Enum patterns in my OSS book : https://basarat.gitbook.io/typescript/type-system/enums

Make sure to use this if you are using the typescript flag --noImplicitAny:

var color : Color = Color[green as keyof typeof Color];

Code Snippets

enum Color{
    Red, Green
}

// To String
 var green: string = Color[Color.Green];

// To Enum / number
var color : Color = Color[green];
var color : Color = Color[green as keyof typeof Color];

Context

Stack Overflow Q#17380845, score: 891

Revisions (0)

No revisions yet.