Starting with TypeScript 0.9.7, accessing an enum value via a string got a little bit inconveniant.
Before 0.9.7 you could do
enum Color { RED, GREEN, BLUE } var colorString = "RED"; var enumVal = Color[colorString];
In 0.9.7, this will report “Index signature of object type implicitly has an ‘any’ type”. According to Microsoft, this is intended behavior.
At the moment, there are three workarounds:
- Define an indexer on the Object interface:
interface Object { [idx: string]: any; }
Now you can access the enum value as follows:
var enumVal: Color = Color[colorString];
The downside is that you can now access properties of any Object via a string.
- Use type casting
You can cast the enum to any:
var enumVal: Color = (<any>Color)[colorString];
- Use an intermediary value that provides an indexer:
var Color2: { [idx: string]: Color; } = <any>Color; var enumVal = Color2[enumString];
As all of the workarounds listed above are a litte bit inconveniant, there is already a ticket to improve enums in a future TypeScript version.
Einsortiert unter:Web as a Platform Tagged: enum, javascript, String, TypeScript
