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

其他回答

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

操场上

我也有同样的问题,然后想出了一个很好用的函数:

每个条目的键和值都是字符串,并且相同。 每个条目的值都是从键派生出来的。(即。“不要重复你自己”,不像字符串值的常规枚举) TypeScript类型成熟且正确。(防止拼写错误) 还有一种简单的方法可以让TS自动完成您的选项。(如。打字MyEnum。,并立即看到可用的选项) 还有其他一些优点。(见答案底部)

效用函数:

export function createStringEnum<T extends {[key: string]: 1}>(keysObj: T) {
    const optionsObj = {} as {
        [K in keyof T]: keyof T
        // alternative; gives narrower type for MyEnum.XXX
        //[K in keyof T]: K
    };
    const keys = Object.keys(keysObj) as Array<keyof T>;
    const values = keys; // could also check for string value-overrides on keysObj
    for (const key of keys) {
        optionsObj[key] = key;
    }
    return [optionsObj, values] as const;
}

用法:

// if the "Fruit_values" var isn't useful to you, just omit it
export const [Fruit, Fruit_values] = createStringEnum({
    apple: 1,
    pear: 1,
});
export type Fruit = keyof typeof Fruit; // "apple" | "pear"
//export type Fruit = typeof Fruit_values[number]; // alternative

// correct usage (with correct types)
let fruit1 = Fruit.apple; // fruit1 == "apple"
fruit1 = Fruit.pear; // assigning a new fruit also works
let fruit2 = Fruit_values[0]; // fruit2 == "apple"

// incorrect usage (should error)
let fruit3 = Fruit.tire; // errors
let fruit4: Fruit = "mirror"; // errors

现在有人可能会问,这个“基于字符串的enum”比只使用:

type Fruit = "apple" | "pear";

有几个优点:

Auto-complete is a bit nicer (imo). For example, if you type let fruit = Fruit., Typescript will immediately list the exact set of options available. With string literals, you need to define your type explicitly, eg. let fruit: Fruit = , and then press ctrl+space afterward. (and even that results in unrelated autocomplete options being shown below the valid ones) The TSDoc metadata/description for an option is carried over to the MyEnum.XXX fields! This is useful for providing additional information about the different options. For example: You can access the list of options at runtime (eg. Fruit_values, or manually with Object.values(Fruit)). With the type Fruit = ... approach, there is no built-in way to do this, which cuts off a number of use-cases. (for example, I use the runtime values for constructing json-schemas)

//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'
export enum PaymentType {
                Cash = 1,
                Credit = 2
            }
var paymentType = PaymentType[PaymentType.Cash];