Quantcast
Channel: techscouting through the java news » Sönke Sothmann
Viewing all articles
Browse latest Browse all 72

TypeScript – Accessing Enum Values via a String

$
0
0

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.


    Einsortiert unter:Web as a Platform Tagged: enum, javascript, String, TypeScript

Viewing all articles
Browse latest Browse all 72

Trending Articles