关于typescript:创建一个包含字符串值的枚举

Create an enum with string values

以下代码可用于在typescript中创建enum

1
2
3
4
enum e {
    hello = 1,
    world = 2
};

这些值可以通过以下方式访问:

1
2
e.hello;
e.world;

如何用字符串值创建enum

1
2
3
4
enum e {
    hello ="hello", // error: cannot convert string to e
    world ="world"  // error
};


Typescrit 2.4(P)Now has string enums so your code just works:(p)字母名称(P)是是(p)typescript 1.8(P)自从typescrit 1.8以来,你可以使用严格的字体类型来提供一种可靠和安全的经验,用于地名的划线(这是一个组成部分,说明什么是使用的)。(p)字母名称(P)More:https://www.typescriplang.org/docs/handbook/advanced-types.html%(p)Legacy Support(P)Enums in typescrit are based number.(p)(P)You can use a class with static members though:(p)字母名称(P)You could go plain as well:(p)字母名称(P)Update:2.Based on the requirement to be able to do some like EDOCX1 simplication satisf0.(p)字母名称


(P)In later version(1.0RC)of typescrit,you can use enums like this:(p)字母名称(P)Update 1(p)(P)To get number value of enum member from string value,you can use this:(p)字母名称(P)Update 2(p)(P)In later typescrit 2.4,there was introduced string enums,like this:(p)字母名称(P)For more info about typescript 2.4,read blog on msdn.(p)


(P)Typescript 2.4+(p)(P)You can now assign string values directly to enum members:(p)字母名称(P)See§35;15486 for more information.(p)(P)Typescript 1.8+(p)(P)在typescript 1.8+,你可以创建一个字体类型来定义样式和一个目标,用同样的名称列出价值清单。It mimics a string enum's expected behaviour.(p)(P)这里是一个例子:(p)字母名称(P)Which will work like a string enum:(p)字母名称(P)让所有的脱衣舞都在目标上!如果你不在第一个例子中提到这个变量,那就不意味着有人要写一个字母。(p)


(P)在Typescrut 0.9.0.1中,尽管这是一个编译错误,但编译者仍然可以将这些文件编入JS文件。《作为我们预期成果和视觉工作室的法典》可支持自动法典的完成。(p)(P)Update:(p)(P)In syntax,typescrit doesn't allow us to create an enum with string values,but we can hack the compiler:p(p)字母名称(P)">Playground(p)


手写体2.1+

typescript 2.1中引入的查找类型允许模拟字符串枚举的其他模式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 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');            // ??

手写体2.4+

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

1
2
3
4
5
enum Colors {
  Red ="RED",
  Green ="GREEN",
  Blue ="BLUE",
}


(P)为什么不只是使用土著人的方式获得一个清单。(p)字母名称


(P)You can use string enums in the latest typescrit:(p)字母名称(P)Source:https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescrit/(p)(P)Update-2016(p)(P)a slightly more stric way of making a set of strings that I use for reach these days is like this:(p)字母名称


这里有一个相当干净的解决方案,允许使用typescript 2.0继承。我没有在早期版本上尝试过。

奖励:该值可以是任何类型!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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: // ...
}


(P)一条通往这条路:(p)(P)Callstatus.(p)字母名称(P)Utils.ts(p)字母名称(P)如何使用(p)字母名称


(P)This works for me:(p)字母名称(P)或(p)字母名称(P)(8)(p)(P)Update:shortly after posting this I discovered another way,but forgot to post an update(however,some already did mentioned it above):(p)字母名称


手写体2.1

也可以这样做。希望它能帮助别人。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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


(P)I just declare an interface and use a variable of that type access the enum.Keeping the interface and enum in sync is actually easy,since typescript complains if some changes in the enum,like so.(p)布尔奇1(P)这一方法的优点是,在不同的情况下,必须采用不同类型的情况,包括不同类型的情况,作为瑞士/案例的情况,采用这一方法。(p)字母名称(P)Using the variable,rather than the enum,produces the desired results.(p)字母名称(P)Flags were another necessity for me,so I created an NPM module that adds to this example,and includes tests.(p)(P)http://github.com/djabraham/ts-enum-tools(p)


有很多答案,但我看不到任何完整的解决方案。接受的答案以及enum { this, one }的问题在于,它分散了您碰巧通过许多文件使用的字符串值。我也不太喜欢"更新",它很复杂,而且也不能利用类型。我认为迈克尔布罗姆利的回答是最正确的,但它的界面有点麻烦,可以用一种类型。

我用的是typescript 2.0.*这是我要做的

1
2
3
4
5
export type Greeting ="hello" |"world";
export const Greeting : { hello: Greeting , world: Greeting } = {
    hello:"hello",
    world:"world"
};

江户十一〔一〕号

在使用有用的IDE时,它还具有更好的类型/悬停信息。回退是你必须写两次字符串,但至少只有两个地方。


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

请看我的NPM包,TS变压器枚举。

示例用法:

1
2
3
4
5
6
7
8
9
// 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'


打字稿<2.4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/** 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

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


@巴沙拉的回答很好。这里有一个简化但有点扩展的示例,您可以使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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...
}


(P)Faced this issue recently with typescript 1.0.1,and solved this way:(p)字母名称


非常、非常、非常简单的带字符串的枚举(typescript 2.4)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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))
}


如果您想要的主要是易于调试(具有相当的类型检查),并且不需要为枚举指定特殊的值,那么这就是我要做的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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);

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

这样,就可以避免键入两次值。


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

(P)I have tried in typescrit 1.5 like below and it's worked for me(p)字母名称


小JS hacky but works:e[String(e.hello)]


1
2
3
4
5
6
7
8
9
10
11
12
//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]);
}


我在寻找一种在typescript-enums(v2.5)中实现描述的方法,这种模式对我很有用:

1
2
3
4
5
6
7
8
9
10
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
}

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


(P)I think you should try with this,in this case the value of the variable won't change and i t works quite like enums,using like a class also works the only disadvantage i s by mistake you can change the value of static variable and that's what we don't want in enums.(p)字母名称


(P)Typescrit 0.9.0.1(p)字母名称(P)typescript playground(p)