TypeScript – Accessing Enum Values via a String

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:

  1. 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.

  2. Use type casting

    You can cast the enum to any:

    var enumVal: Color = (<any>Color)[colorString];
    
  3. Use an intermediary value that provides an indexer:
    var Color2: { [idx: string]: Color; } = <any>Color;
    var enumVal = Color2[enumString];
    
  4. 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.

    Short URL for this post: http://wp.me/p4nxik-1QQ
This entry was posted in Web as a Platform and tagged , , , . Bookmark the permalink.

Leave a Reply