adplus-dvertising

How do I convert a string to enum in TypeScript?

Asked 9 years ago
Viewed 407.8 k times

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?

asked 9 years ago

Correct 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.gitbook.io/typescript/type-system/enums

answered 3 years ago

Other Answer

As of Typescript 2.1 string keys in enums are strongly typed. keyof typeof is used to get info about available string keys (1):

enum Color{
    Red, Green
}

let typedColor: Color = Color.Green;
let typedColorString: keyof typeof Color = "Green";

// Error "Black is not assignable ..." (indexing using Color["Black"] will return undefined runtime)
typedColorString = "Black";

// Error "Type 'string' is not assignable ..." (indexing works runtime)
let letColorString = "Red";
typedColorString = letColorString;

// Works fine
typedColorString = "Red";

// Works fine
const constColorString = "Red";
typedColorString = constColorString

// Works fine (thanks @SergeyT)
let letColorString = "Red";
typedColorString = letColorString as keyof typeof Color;

typedColor = Color[typedColorString];

https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types

answered 9 years ago