使用字符串值创建枚举

时间:2013-03-19 02:32:45

标签: typescript

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

28 个答案:

答案 0 :(得分:354)

TypeScript 2.4

现在有字符串枚举,所以你的代码正常工作:

enum E {
    hello = "hello",
    world = "world"
};

TypeScript 1.8

从TypeScript 1.8开始,您可以使用字符串文字类型为命名字符串值(部分用于枚举的部分)提供可靠且安全的体验。

type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay 
foo = "asdf"; // Error!

更多:https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types

遗产支持

TypeScript中的枚举是基于数字的。

您可以使用具有静态成员的类:

class E
{
    static hello = "hello";
    static world = "world"; 
}

你也可以说清楚:

var E = {
    hello: "hello",
    world: "world"
}

<强>更新 根据能够执行var test:E = E.hello;之类的要求,以下内容满足:

class E
{
    // boilerplate 
    constructor(public value:string){    
    }

    toString(){
        return this.value;
    }

    // values 
    static hello = new E("hello");
    static world = new E("world");
}

// Sample usage: 
var first:E = E.hello;
var second:E = E.world;
var third:E = E.hello;

console.log("First value is: "+ first);
console.log(first===third); 

答案 1 :(得分:106)

在TypeScript的最新版本(1.0RC)中,您可以使用以下枚举:

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

要从字符串值获取枚举成员的数值,可以使用:

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

更新2

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

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

    // Aliases
    RemoveUser = DeleteUser,
}

有关TypeScript 2.4的详细信息,请阅读blog on MSDN

答案 2 :(得分:78)

TypeScript 2.4 +

您现在可以直接将字符串值分配给枚举成员:

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

有关详细信息,请参阅#15486

TypeScript 1.8 +

在TypeScript 1.8+中,您可以创建字符串文字类型来定义类型,并为值列表指定具有相同名称的对象。它模仿字符串枚举的预期行为。

以下是一个例子:

type MyStringEnum = "member1" | "member2";

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

这将像字符串枚举一样工作:

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

答案 3 :(得分:40)

在TypeScript 0.9.0.1中,虽然它发生编译器错误,但编译器仍然可以将ts文件编译为js文件。代码按预期工作,Visual Studio 2012可以支持自动代码完成。

更新:

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

Playground

答案 4 :(得分:22)

TypeScript 2.1 +

在TypeScript 2.1中引入的

Lookup types允许另一种模式来模拟字符串枚举:

// String enums in TypeScript 2.1
const EntityType = {
    Foo: 'Foo' as 'Foo',
    Bar: 'Bar' as 'Bar'
};

function doIt(entity: keyof typeof EntityType) {
    // ...
}

EntityType.Foo          // 'Foo'
doIt(EntityType.Foo);   // 
doIt(EntityType.Bar);   // 
doIt('Foo');            // 
doIt('Bad');            //  

TypeScript 2.4 +

对于2.4版本,TypeScript引入了对字符串枚举的本机支持,因此不需要上述解决方案。来自TS文档:

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}

答案 5 :(得分:19)

为什么不使用本地方式访问枚举字符串。

enum e {
  WHY,
  NOT,
  USE,
  NATIVE
}

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

答案 6 :(得分:16)

您可以在最新的TypeScript中使用字符串枚举:

enum e
{
    hello = <any>"hello",
    world = <any>"world"
};

来源:https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/

更新 - 2016

现在用于React的一组字符串稍微强一些的方法是这样的:

export class Messages
{
    static CouldNotValidateRequest: string = 'There was an error validating the request';
    static PasswordMustNotBeBlank: string = 'Password must not be blank';   
}

import {Messages as msg} from '../core/messages';
console.log(msg.PasswordMustNotBeBlank);

答案 7 :(得分:10)

这是一个相当干净的解决方案,允许继承,使用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: // ...
}

答案 8 :(得分:8)

一种愚蠢的方法是: -

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"

答案 9 :(得分:7)

这对我有用:

class MyClass {
    static MyEnum: { Value1; Value2; Value3; }
    = {
        Value1: "Value1",
        Value2: "Value2",
        Value3: "Value3"
    };
}

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

答案 10 :(得分:4)

TypeScript 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

答案 11 :(得分:3)

我只声明一个接口并使用该类型的变量访问枚举。保持接口和枚举同步实际上很容易,因为如果枚举中的某些内容发生变化,TypeScript会抱怨,就像这样。

  

错误TS2345:EAbFlagEnum&#39;类型&#39;类型的参数不可分配   参数类型&#39; IAbFlagEnum&#39;。物业&#39;移动&#39;在类型中缺失   &#39;类型EAbFlagEnum&#39;。

这种方法的优点是不需要进行类型转换,以便在各种情况下使用枚举(接口),从而支持更多类型的情况,例如开关/情况。

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

答案 12 :(得分:2)

TypeScript&lt; 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

在源链接中,您可以找到更多更简单的方法来完成字符串文字类型

答案 13 :(得分:2)

有很多答案,但我没有看到任何完整的解决方案。接受的答案以及enum { this, one }的问题在于它通过许多文件分散您恰好使用的字符串值。我不太喜欢&#34;更新&#34;或者,它很复杂,也不利用类型。我认为Michael Bromley's answer是最正确的,但它的界面有点麻烦,可以用一种类型。

我正在使用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时,它还具有更好的类型/悬停信息。退回是你必须两次写字符串,但至少它只在两个地方。

答案 14 :(得分:2)

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

请查看我的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'

答案 15 :(得分:1)

最近使用TypeScript 1.0.1面对此问题,并以这种方式解决:

enum IEvents {
        /** A click on a product or product link for one or more products. */
        CLICK,
        /** A view of product details. */
        DETAIL,
        /** Adding one or more products to a shopping cart. */
        ADD,
        /** Remove one or more products from a shopping cart. */
        REMOVE,
        /** Initiating the checkout process for one or more products. */
        CHECKOUT,
        /** Sending the option value for a given checkout step. */
        CHECKOUT_OPTION,
        /** The sale of one or more products. */
        PURCHASE,
        /** The refund of one or more products. */
        REFUND,
        /** A click on an internal promotion. */
        PROMO_CLICK
}

var Events = [
        'click',
        'detail',
        'add',
        'remove',
        'checkout',
        'checkout_option',
        'purchase',
        'refund',
        'promo_click'
];

function stuff(event: IEvents):boolean {
        // event can now be only IEvents constants
        Events[event]; // event is actually a number that matches the index of the array
}
// stuff('click') won't work, it needs to be called using stuff(IEvents.CLICK)

答案 16 :(得分:1)

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

答案 17 :(得分:0)

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

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

现在有人可能会问,这个“基于字符串的枚举”比仅仅使用有什么优势:

type Fruit = "apple" | "pear";

有几个优点:

  1. 自动完成更好一些 (imo)。例如,如果您键入 let fruit = Fruit.,Typescript 将立即列出可用选项的确切集合。使用字符串文字,您需要明确定义您的类型,例如。 let fruit: Fruit = ,然后按 ctrl+space。 (甚至会导致不相关的自动完成选项显示在有效选项下方)
  2. 选项的 TSDoc 元数据/描述被转移到 MyEnum.XXX 字段!这对于提供有关不同选项的附加信息很有用。例如:
  3. 您可以在运行时访问选项列表(例如,Fruit_values,或手动使用 Object.values(Fruit))。使用 type Fruit = ... 方法时,没有内置的方法来执行此操作,这会切断许多用例。 (例如,我使用运行时值来构建 json-schema)

答案 18 :(得分:0)

我一直在寻找一种在打字稿枚举(v2.5)中实现描述的方法,这种模式对我有用:

export enum PriceTypes {
    Undefined = 0,
    UndefinedDescription = 'Undefined' as any,
    UserEntered = 1,
    UserEnteredDescription = 'User Entered' as any,
    GeneratedFromTrade = 2,
    GeneratedFromTradeDescription = 'Generated From Trade' as any,
    GeneratedFromFreeze = 3,
    GeneratedFromFreezeDescription = 'Generated Rom Freeze' as any
}

...

    GetDescription(e: any, id: number): string {
        return e[e[id].toString() + "Description"];
    }
    getPriceTypeDescription(price: IPricePoint): string {
        return this.GetDescription(PriceTypes, price.priceType);
    }

答案 19 :(得分:0)

Typescript 中的字符串枚举:

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

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

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

enter link description here

答案 20 :(得分:0)

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

答案 21 :(得分:0)

如果您想要的主要是简单的调试(使用相当类型的检查)并且不需要为枚举指定特殊值,这就是我正在做的:

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

如果您想支持旧版代码/数据存储,可以保留数字键。

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

答案 22 :(得分:0)

小js-hacky但有效:e[String(e.hello)]

答案 23 :(得分:0)

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

答案 24 :(得分:0)

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

答案 25 :(得分:0)

我已尝试使用类似于下面的TypeScript 1.5并且它为我工作

module App.Constants {
   export enum e{
        Hello= ("Hello") as any,
World= ("World") as any
    }
}

答案 26 :(得分:0)

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

namespace portal {

export namespace storageNames {

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

  }
}

答案 27 :(得分:-2)

TypeScript 0.9.0.1

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

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

TypeScript Playground