FacePalm FacePalm - 1 month ago 12
TypeScript Question

Create an enum with string values in Typescript

Following code can be used to create an enum in Typescript :

enum e{
hello = 1,
world = 2
};


and the values can be accessed by :

e.hello;
e.world;


How do I create an enum with string values ?

enum e{
hello = "hello", //error :cannot convert string to e
world = "world" //error
};

Answer

Way forward

Since TypeScript 1.8 you can use string literal types to provide a reliable and safe experience for named string values (which is partially what enums are used for).

type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay 
foo = "asdf"; // Error!

More : https://basarat.gitbooks.io/typescript/content/docs/types/stringLiteralType.html

Legacy Support

Enums in Typescript are number based.

You can use a class with static members though:

class E
{
    static hello = "hello";
    static world = "world"; 
}

You could go plain as well:

var E = {
    hello: "hello",
    world: "world"
}

Update: Based on the requirement to be able to do something like var test:E = E.hello; the following satisfies this:

class E
{
    // boilerplate 
    constructor(public value:string){    
    }

    toString(){
        return this.value;
    }

    // values 
    static hello = new E("hello");
    static world = new E("world");
}

// Sample usage: 
var first:E = E.hello;
var second:E = E.world;
var third:E = E.hello;

console.log("First value is: "+ first);
console.log(first===third);