Allow for "String Enumerations"

Issue #119 new
Brandon Bell
created an issue

It would be nice to allow for string enumeration generation. While string enumerations technically don't yet exist with TypeScript, there is an easy way to simulate them in TypeScript 1.8+:

type MyStringEnum = "Member1" | "Member2";

const MyStringEnum = {
    Member1: "Member1" as MyStringEnum,
    Member2: "Member2" as MyStringEnum

This allows for behavior like a string enumeration:

// implicit typing example
let myVariable = MyStringEnum.Member1; // ok
myVariable = "Member2";                // ok
myVariable = "some other value";       // error, desired

// explict typing example
let myExplicitlyTypedVariable: MyStringEnum;
myExplicitlyTypedVariable = MyStringEnum.Member1; // ok
myExplicitlyTypedVariable = "Member2";            // ok
myExplicitlyTypedVariable = "some other value";   // error, desired

The reason why this is nice is that web services often serialize enumerations as the string value, rather than an integer value, and so the typing doesn't end up working properly.

Comments (2)

  1. Richard Lawley

    I've actually created my own generator which does this - the only reason I haven't fed it back in yet is because it's not as simple as you might think - the "const" part cannot exist within a .d.ts file (the compiler doesn't allow the = bit, with the error "Initializers are not allowed in ambient contexts"). In my own solution, I'm outputting everything into a separate .ts file, but this isn't ideal either as you now have to specifically import the generated types in order to use them.

  2. Log in to comment