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?
27 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];
I have documention about this and other Enum patterns in my OSS book :
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];
enum Color{
Red, Green
}
// To String
var green: string = Color[Color.Green];
// To Enum / number
var color : Color = Color[green as keyof typeof Color]; //Works with --noImplicitAny
This example works with --noImplicitAny in TypeScript
Sources:
If you provide string values to your enum, a straight cast works just fine.
enum Color {
Green = "Green",
Red = "Red"
}
const color = "Green";
const colorEnum = color as Color;
Given you use typescript: Many of the solutions above might not work or are overly complex.
Situation: The strings are not the same as the enum values (casing differs)
enum Color {
Green = "green",
Red = "red"
}
Just use:
const color = "green" as Color
Please note that this does not guarantee a valid enum.
Typescript 1.x
If you are sure that an input string has an exact match with Color enum then use:
const color: Color = (<any>Color)["Red"];
In the case where an input string may not match Enum, use:
const mayBeColor: Color | undefined = (<any>Color)["WrongInput"];
if (mayBeColor !== undefined){
// TypeScript will understand that mayBeColor is of type Color here
}
If we do not cast enum to <any> type then TypeScript will show the error:
Element implicitly has 'any' type because index expression is not of type 'number'.
It means that by default the TypeScript Enum type works with number indexes, i.e.
let c = Color[0], but not with string indexes like let c = Color["string"]. This is a known restriction by the Microsoft team for the more general issue Object string indexes.