[typescript] How do I convert a string to enum in TypeScript?

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
}

Playground


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.