HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCritical

Create an enum with string values

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
enumwithstringvaluescreate

Problem

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 
};

Solution

TypeScript 2.4

Now has string enums so your code just works:

enum E {
    hello = "hello",
    world = "world"
};


🌹

TypeScript 1.8

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://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types

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);

Code Snippets

enum E {
    hello = "hello",
    world = "world"
};
type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay 
foo = "asdf"; // Error!
class E
{
    static hello = "hello";
    static world = "world"; 
}
var E = {
    hello: "hello",
    world: "world"
}
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);

Context

Stack Overflow Q#15490560, score: 556

Revisions (0)

No revisions yet.