以下代码可用于在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 
};

当前回答

这里有一个相当干净的解决方案,它允许继承,使用TypeScript 2.0。我没有在早期的版本上尝试过。

附加条件:该值可以是任何类型!

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: // ...
}

其他回答

在最新版本(1.0RC)的TypeScript中,你可以像这样使用枚举:

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

更新1

要从string value中获取enum成员的number值,你可以使用这个:

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

更新2

在最新的TypeScript 2.4中,引入了字符串enum,如下所示:

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

    // Aliases
    RemoveUser = DeleteUser,
}

有关TypeScript 2.4的更多信息,请阅读MSDN上的博客。

如果你想要的主要是易于调试(相当类型检查),不需要为枚举指定特殊值,这是我正在做的:

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

如果您希望支持遗留代码/数据存储,则可以保留数字键。

这样,您就可以避免键入两次值。

一个俗套的说法是:-

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

如何使用

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

TypeScript 2 + 4。

你现在可以直接将字符串值分配给enum成员:

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

更多信息见#15486。

打印稿1.8 +

在TypeScript 1.8+中,你可以创建一个字符串文字类型来定义类型,并为值列表创建一个同名的对象。它模仿字符串enum的预期行为。

这里有一个例子:

type MyStringEnum = "member1" | "member2";

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

它将像字符串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

确保输入对象中的所有字符串!如果不这样做,那么在上面的第一个例子中,变量将不会隐式地类型化为MyStringEnum。

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