[typescript] Create an enum with string values

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

This question is related to typescript

The answer is


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

Little js-hacky but works: e[String(e.hello)]


export enum PaymentType {
                Cash = 1,
                Credit = 2
            }
var paymentType = PaymentType[PaymentType.Cash];

There a lot of answers, but I don't see any complete solutions. The problem with the accepted answer, as well as enum { this, one }, is that it disperses the string value you happen to be using through many files. I don't really like the "update" either, it's complex and doesn't leverage types as well. I think Michael Bromley's answer is most correct, but it's interface is a bit of a hassle and could do with a type.

I am using TypeScript 2.0.+ ... Here's what I would do

export type Greeting = "hello" | "world";
export const Greeting : { hello: Greeting , world: Greeting } = {
    hello: "hello",
    world: "world"
};

Then use like this:

let greet: Greeting = Greeting.hello

It also has much nicer type / hover-over information when using a helpful IDE. The draw back is you have to write the strings twice, but at least it's only in two places.


Very, very, very simple Enum with string (TypeScript 2.4)

import * from '../mylib'

export enum MESSAGES {
    ERROR_CHART_UNKNOWN,
    ERROR_2
}

export class Messages {
    public static get(id : MESSAGES){
        let message = ""
        switch (id) {
            case MESSAGES.ERROR_CHART_UNKNOWN :
                message = "The chart does not exist."
                break;
            case MESSAGES.ERROR_2 :
                message = "example."
                break;
        }
        return message
    }
}

function log(messageName:MESSAGES){
    console.log(Messages.get(messageName))
}

Faced this issue recently with TypeScript 1.0.1, and solved this way:

enum IEvents {
        /** A click on a product or product link for one or more products. */
        CLICK,
        /** A view of product details. */
        DETAIL,
        /** Adding one or more products to a shopping cart. */
        ADD,
        /** Remove one or more products from a shopping cart. */
        REMOVE,
        /** Initiating the checkout process for one or more products. */
        CHECKOUT,
        /** Sending the option value for a given checkout step. */
        CHECKOUT_OPTION,
        /** The sale of one or more products. */
        PURCHASE,
        /** The refund of one or more products. */
        REFUND,
        /** A click on an internal promotion. */
        PROMO_CLICK
}

var Events = [
        'click',
        'detail',
        'add',
        'remove',
        'checkout',
        'checkout_option',
        'purchase',
        'refund',
        'promo_click'
];

function stuff(event: IEvents):boolean {
        // event can now be only IEvents constants
        Events[event]; // event is actually a number that matches the index of the array
}
// stuff('click') won't work, it needs to be called using stuff(IEvents.CLICK)

In TypeScript 0.9.0.1, although it occurs a compiler error, the compiler can still compile the ts file into js file. The code works as we expected and Visual Studio 2012 can support for automatic code completion.

Update :

In syntax, TypeScript doesn't allow us to create an enum with string values, but we can hack the compiler :p

enum Link
{
    LEARN   =   <any>'/Tutorial',
    PLAY    =   <any>'/Playground',
    GET_IT  =   <any>'/#Download',
    RUN_IT  =   <any>'/Samples',
    JOIN_IN =   <any>'/#Community'
}

alert('Link.LEARN:    '                     + Link.LEARN);
alert('Link.PLAY:    '                      + Link.PLAY);
alert('Link.GET_IT:    '                    + Link.GET_IT);
alert('Link[\'/Samples\']:    Link.'        + Link['/Samples']);
alert('Link[\'/#Community\']    Link.'      + Link['/#Community']);

Playground


I think you should try with this, in this case the value of the variable won't change and it works quite like enums,using like a class also works the only disadvantage is by mistake you can change the value of static variable and that's what we don't want in enums.

namespace portal {

export namespace storageNames {

    export const appRegistration = 'appRegistration';
    export const accessToken = 'access_token';

  }
}

@basarat's answer was great. Here is simplified but a little bit extended example you can use:

export type TMyEnumType = 'value1'|'value2';

export class MyEnumType {
    static VALUE1: TMyEnumType = 'value1';
    static VALUE2: TMyEnumType = 'value2';
}

console.log(MyEnumType.VALUE1); // 'value1'

const variable = MyEnumType.VALUE2; // it has the string value 'value2'

switch (variable) {
    case MyEnumType.VALUE1:
        // code...

    case MyEnumType.VALUE2:
        // code...
}

I just declare an interface and use a variable of that type access the enum. Keeping the interface and enum in sync is actually easy, since TypeScript complains if something changes in the enum, like so.

error TS2345: Argument of type 'typeof EAbFlagEnum' is not assignable to parameter of type 'IAbFlagEnum'. Property 'Move' is missing in type 'typeof EAbFlagEnum'.

The advantage of this method is no type casting is required in order to use the enum (interface) in various situations, and more types of situations are thus supported, such as the switch/case.

// Declare a TypeScript enum using unique string 
//  (per hack mentioned by zjc0816)

enum EAbFlagEnum {
  None      = <any> "none",
  Select    = <any> "sel",
  Move      = <any> "mov",
  Edit      = <any> "edit",
  Sort      = <any> "sort",
  Clone     = <any> "clone"
}

// Create an interface that shadows the enum
//   and asserts that members are a type of any

interface IAbFlagEnum {
    None:   any;
    Select: any;
    Move:   any;
    Edit:   any;
    Sort:   any;
    Clone:  any;
}

// Export a variable of type interface that points to the enum

export var AbFlagEnum: IAbFlagEnum = EAbFlagEnum;

Using the variable, rather than the enum, produces the desired results.

var strVal: string = AbFlagEnum.Edit;

switch (strVal) {
  case AbFlagEnum.Edit:
    break;
  case AbFlagEnum.Move:
    break;
  case AbFlagEnum.Clone
}

Flags were another necessity for me, so I created an NPM module that adds to this example, and includes tests.

https://github.com/djabraham/ts-enum-tools


i was looking for a way to implement descriptions in typescript enums (v2.5) and this pattern worked for me:

export enum PriceTypes {
    Undefined = 0,
    UndefinedDescription = 'Undefined' as any,
    UserEntered = 1,
    UserEnteredDescription = 'User Entered' as any,
    GeneratedFromTrade = 2,
    GeneratedFromTradeDescription = 'Generated From Trade' as any,
    GeneratedFromFreeze = 3,
    GeneratedFromFreezeDescription = 'Generated Rom Freeze' as any
}

...

    GetDescription(e: any, id: number): string {
        return e[e[id].toString() + "Description"];
    }
    getPriceTypeDescription(price: IPricePoint): string {
        return this.GetDescription(PriceTypes, price.priceType);
    }

You can use string enums in the latest TypeScript:

enum e
{
    hello = <any>"hello",
    world = <any>"world"
};

Source: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/


UPDATE - 2016

A slightly more robust way of making a set of strings that I use for React these days is like this:

export class Messages
{
    static CouldNotValidateRequest: string = 'There was an error validating the request';
    static PasswordMustNotBeBlank: string = 'Password must not be blank';   
}

import {Messages as msg} from '../core/messages';
console.log(msg.PasswordMustNotBeBlank);

This works for me:

class MyClass {
    static MyEnum: { Value1; Value2; Value3; }
    = {
        Value1: "Value1",
        Value2: "Value2",
        Value3: "Value3"
    };
}

or

module MyModule {
    export var MyEnum: { Value1; Value2; Value3; }
    = {
        Value1: "Value1",
        Value2: "Value2",
        Value3: "Value3"
    };
}

8)

Update: Shortly after posting this I discovered another way, but forgot to post an update (however, someone already did mentioned it above):

enum MyEnum {
    value1 = <any>"value1 ", 
    value2 = <any>"value2 ", 
    value3 = <any>"value3 " 
}

UPDATE: TypeScript 3.4

You can simply use as const:

const AwesomeType = {
   Foo: "foo",
   Bar: "bar"
} as const;

TypeScript 2.1

This can also be done this way. Hope it help somebody.

const AwesomeType = {
    Foo: "foo" as "foo",
    Bar: "bar" as "bar"
};

type AwesomeType = (typeof AwesomeType)[keyof typeof AwesomeType];

console.log(AwesomeType.Bar); // returns bar
console.log(AwesomeType.Foo); // returns foo

function doSth(awesometype: AwesomeType) {
    console.log(awesometype);
}

doSth("foo") // return foo
doSth("bar") // returns bar
doSth(AwesomeType.Bar) // returns bar
doSth(AwesomeType.Foo) // returns foo
doSth('error') // does not compile

TypeScript 0.9.0.1

enum e{
    hello = 1,
    somestr = 'world'
};

alert(e[1] + ' ' + e.somestr);

TypeScript Playground


TypeScript < 2.4

/** Utility function to create a K:V from a list of strings */
function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
  return o.reduce((res, key) => {
    res[key] = key;
    return res;
  }, Object.create(null));
}

/**
  * Sample create a string enum
  */

/** Create a K:V */
const Direction = strEnum([
  'North',
  'South',
  'East',
  'West'
])
/** Create a Type */
type Direction = keyof typeof Direction;

/** 
  * Sample using a string enum
  */
let sample: Direction;

sample = Direction.North; // Okay
sample = 'North'; // Okay
sample = 'AnythingElse'; // ERROR!

from https://basarat.gitbooks.io/typescript/docs/types/literal-types.html

To the source link you can find more and easier ways to accomplish string literal type


In latest version (1.0RC) of TypeScript, you can use enums like this:

enum States {
    New,
    Active,
    Disabled
} 

// this will show message '0' which is number representation of enum member
alert(States.Active); 

// this will show message 'Disabled' as string representation of enum member
alert(States[States.Disabled]);

Update 1

To get number value of enum member from string value, you can use this:

var str = "Active";
// this will show message '1'
alert(States[str]);

Update 2

In latest TypeScript 2.4, there was introduced string enums, like this:

enum ActionType {
    AddUser = "ADD_USER",
    DeleteUser = "DELETE_USER",
    RenameUser = "RENAME_USER",

    // Aliases
    RemoveUser = DeleteUser,
}

For more info about TypeScript 2.4, read blog on MSDN.


I have tried in TypeScript 1.5 like below and it's worked for me

module App.Constants {
   export enum e{
        Hello= ("Hello") as any,
World= ("World") as any
    }
}

If what you want is mainly easy debug (with fairly type check) and don't need to specify special values for the enum, this is what I'm doing:

export type Enum = { [index: number]: string } & { [key: string]: number } | Object;

/**
 * inplace update
 * */
export function enum_only_string<E extends Enum>(e: E) {
  Object.keys(e)
    .filter(i => Number.isFinite(+i))
    .forEach(i => {
      const s = e[i];
      e[s] = s;
      delete e[i];
    });
}

enum AuthType {
  phone, email, sms, password
}
enum_only_string(AuthType);

If you want to support legacy code/data storage, you might keep the numeric keys.

This way, you can avoid typing the values twice.


TypeScript 2.4+

You can now assign string values directly to enum members:

enum Season {
    Winter = "winter",
    Spring = "spring",
    Summer = "summer",
    Fall = "fall"
}

See #15486 for more information.

TypeScript 1.8+

In TypeScript 1.8+, you can create a string literal type to define the type and an object with the same name for the list of values. It mimics a string enum's expected behaviour.

Here's an example:

type MyStringEnum = "member1" | "member2";

const MyStringEnum = {
    Member1: "member1" as MyStringEnum,
    Member2: "member2" as MyStringEnum
};

Which will work like a string enum:

// 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

Make sure to type all the strings in the object! If you don't then in the first example above the variable would not be implicitly typed to MyStringEnum.


TypeScript 2.1 +

Lookup types, introduced in TypeScript 2.1 allow another pattern for simulating string enums:

// String enums in TypeScript 2.1
const EntityType = {
    Foo: 'Foo' as 'Foo',
    Bar: 'Bar' as 'Bar'
};

function doIt(entity: keyof typeof EntityType) {
    // ...
}

EntityType.Foo          // 'Foo'
doIt(EntityType.Foo);   // 
doIt(EntityType.Bar);   // 
doIt('Foo');            // 
doIt('Bad');            //  

TypeScript 2.4 +

With version 2.4, TypeScript introduced native support for string enums, so the solution above is not needed. From the TS docs:

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}

With custom transformers (https://github.com/Microsoft/TypeScript/pull/13940) which is available in typescript@next, you can create enum like object with string values from string literal types.

Please look into my npm package, ts-transformer-enumerate.

Example usage:

// The signature of `enumerate` here is `function enumerate<T extends string>(): { [K in T]: K };`
import { enumerate } from 'ts-transformer-enumerate';

type Colors = 'green' | 'yellow' | 'red';
const Colors = enumerate<Colors>();

console.log(Colors.green); // 'green'
console.log(Colors.yellow); // 'yellow'
console.log(Colors.red); // 'red'

Here's a fairly clean solution that allows inheritance, using TypeScript 2.0. I didn't try this on an earlier version.

Bonus: the value can be any type!

export class Enum<T> {
  public constructor(public readonly value: T) {}
  public toString() {
    return this.value.toString();
  }
}

export class PrimaryColor extends Enum<string> {
  public static readonly Red = new Enum('#FF0000');
  public static readonly Green = new Enum('#00FF00');
  public static readonly Blue = new Enum('#0000FF');
}

export class Color extends PrimaryColor {
  public static readonly White = new Enum('#FFFFFF');
  public static readonly Black = new Enum('#000000');
}

// Usage:

console.log(PrimaryColor.Red);
// Output: Enum { value: '#FF0000' }
console.log(Color.Red); // inherited!
// Output: Enum { value: '#FF0000' }
console.log(Color.Red.value); // we have to call .value to get the value.
// Output: #FF0000
console.log(Color.Red.toString()); // toString() works too.
// Output: #FF0000

class Thing {
  color: Color;
}

let thing: Thing = {
  color: Color.Red,
};

switch (thing.color) {
  case Color.Red: // ...
  case Color.White: // ...
}

A hacky way to this is: -

CallStatus.ts

enum Status
{
    PENDING_SCHEDULING,
    SCHEDULED,
    CANCELLED,
    COMPLETED,
    IN_PROGRESS,
    FAILED,
    POSTPONED
}

export = Status

Utils.ts

static getEnumString(enum:any, key:any):string
{
    return enum[enum[key]];
}

How to use

Utils.getEnumString(Status, Status.COMPLETED); // = "COMPLETED"

Why not just use the native way of accessing the strings of a enum.

enum e {
  WHY,
  NOT,
  USE,
  NATIVE
}

e[e.WHY] // this returns string 'WHY'

//to access the enum with its string value you can convert it to object 
//then you can convert enum to object with proberty 
//for Example :

enum days { "one" =3, "tow", "Three" }

let _days: any = days;

if (_days.one == days.one)
{ 
    alert(_days.one + ' | ' + _days[4]);
}