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

/** Utility function to create a K:V from a list of strings */
function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
  return o.reduce((res, key) => {
    res[key] = key;
    return res;
  }, Object.create(null));
}

/**
  * Sample create a string enum
  */

/** Create a K:V */
const Direction = strEnum([
  'North',
  'South',
  'East',
  'West'
])
/** Create a Type */
type Direction = keyof typeof Direction;

/** 
  * Sample using a string enum
  */
let sample: Direction;

sample = Direction.North; // Okay
sample = 'North'; // Okay
sample = 'AnythingElse'; // ERROR!

从https://basarat.gitbooks.io/typescript/docs/types/literal-types.html

到源代码链接,你可以找到更多更简单的方法来实现字符串文字类型

其他回答

非常非常简单的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中的字符串枚举:

字符串枚举是一个类似的概念,但是有一些细微的运行时差异,如下文所述。在string enum中,每个成员必须用string字面值或另一个string enum成员常量初始化。

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}

虽然字符串枚举没有自动递增的行为,但字符串枚举的好处是它们很好地“序列化”。换句话说,如果你正在调试并且必须读取一个数值enum的运行时值,这个值通常是不透明的——它本身没有传达任何有用的含义(尽管反向映射通常会有所帮助),字符串enum允许你在代码运行时给出一个有意义且可读的值,与枚举成员本身的名称无关。 参考链接如下。

在这里输入链接描述

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

每个条目的键和值都是字符串,并且相同。 每个条目的值都是从键派生出来的。(即。“不要重复你自己”,不像字符串值的常规枚举) 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)

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

enum e {
  WHY,
  NOT,
  USE,
  NATIVE
}

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

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