以下代码可用于在TypeScript中创建enum:

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

这些值可以通过以下方式访问:

e.hello;
e.world;

我如何创建一个字符串值enum ?

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

当前回答

//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]);
}

其他回答

为什么不直接使用本地方式访问枚举的字符串呢?

enum e {
  WHY,
  NOT,
  USE,
  NATIVE
}

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

打印稿0.9.0.1

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

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

打印稿操场

小js-hack但工作:e[字符串(e.hello)]

你可以在最新的TypeScript中使用字符串枚举:

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

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


更新- 2016

最近我在React中使用的一种更健壮的方法是这样的:

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

有很多答案,但我没有看到任何完整的解决方案。可接受的答案以及enum {this, one}的问题是,它分散了您碰巧在许多文件中使用的字符串值。我也不太喜欢“更新”,它很复杂,也没有利用类型。我认为Michael Bromley的回答是最正确的,但它的界面有点麻烦,可以用一个类型。

我使用的是TypeScript 2.0。+……这是我会做的

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

然后像这样使用:

let greet: Greeting = Greeting.hello

在使用有用的IDE时,它还具有更好的类型/悬停信息。缺点是你必须写两次字符串,但至少它只在两个地方。