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

当前回答

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

其他回答

有很多答案,但我没有看到任何完整的解决方案。可接受的答案以及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时,它还具有更好的类型/悬停信息。缺点是你必须写两次字符串,但至少它只在两个地方。

打印稿0.9.0.1

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

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

打印稿操场

这对我来说很管用:

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)

更新:在发布这篇文章后不久,我发现了另一种方法,但忘记发布更新(然而,上面已经有人提到过了):

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

在TypeScript 0.9.0.1中,尽管会出现编译器错误,但编译器仍然可以将ts文件编译为js文件。代码工作如我们所料,Visual Studio 2012可以支持自动代码补全。

更新:

在语法上,TypeScript不允许我们用字符串值创建enum,但我们可以破解编译器: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']);

操场上

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