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

当前回答

我认为你应该试试这个,在这种情况下,变量的值不会改变,它的工作方式很像枚举,使用类也可以,唯一的缺点是你可以错误地改变静态变量的值这是我们不希望在枚举中发生的。

namespace portal {

export namespace storageNames {

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

  }
}

其他回答

我只是声明了一个接口,并使用该类型的变量访问枚举。保持接口和枚举同步实际上很容易,因为如果枚举中有什么变化,TypeScript会报错,就像这样。

typeof EAbFlagEnum类型的参数不可赋值 参数类型为“IAbFlagEnum”。属性“Move”类型缺失 “typeof EAbFlagEnum”。

这种方法的优点是在各种情况下使用enum(接口)不需要类型强制转换,因此支持更多类型的情况,例如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;

使用变量,而不是枚举,可以产生所需的结果。

var strVal: string = AbFlagEnum.Edit;

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

标记是我的另一个需要,所以我创建了一个NPM模块,添加到这个例子中,并包括测试。

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

@basarat的回答很棒。下面是一个你可以使用的简化但有点扩展的例子:

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

非常非常简单的Enum 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))
}

使用typescript@next中提供的自定义转换器(https://github.com/Microsoft/TypeScript/pull/13940),您可以从字符串字面类型创建字符串值的枚举对象。

请查看我的npm包,ts-transformer-enumerate。

使用示例:

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

更新:TypeScript 3.4

你可以简单地使用const:

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

打字稿2.1

这也可以用这种方式完成。希望它能帮助到一些人。

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