简体   繁体   English

如何使用Typescript中的值创建和解析字符串枚举

[英]How to create and parse string enums with values in Typescript

I know that there is issue with creating string enums using Typescript, even in v2.4+ I'm using typescript 2.8 and Angular 6. 我知道使用Typescript创建字符串枚举存在问题,即使在v2.4 +中,我也使用Typescript 2.8和Angular 6。

I would like to have an enum and to freely get string value from enum, and to parse string into enum. 我想要一个枚举,并从枚举中自由获取字符串值,并将字符串解析为枚举。

So assume I have this enum: 所以假设我有这个枚举:

export enum MyEnum{
  INIT = 'init-room',
  CLOSE = 'close-room'
}

This enum is useful to communicate with rest API. 该枚举对与其余API进行通信很有用。 So from API and to API I have to send strings. 因此,从API到API,我必须发送字符串。 But inside app I want to asap convert string from API to enum. 但是在应用程序内部,我想尽快将字符串从API转换为枚举。

So I want to have function to parse, and stringify my enum. 所以我想具有解析和字符串化我的枚举的功能。

I try this approach, but this won't work. 我尝试了这种方法,但是这行不通。

export function toString(type: MyEnum): string {
    return MyEnum[type];
}

export function parse(type: string): Mode {
    return MyEnum[type];
}

Well, it isn't big surprise, because I want to get value from this enum, not MyEnum[type] - but I don't know how to do this. 好吧,这并不奇怪,因为我想从这个枚举中获取value ,而不是MyEnum[type] -但我不知道该怎么做。

I know that there is an issue with converting key to value, while value to key works. 我知道将键转换为值时会遇到问题,而将值转换为键时有效。 So I'm asking for any clean-code solution to achieve my goal. 因此,我需要任何干净的代码解决方案来实现我的目标。

也许尝试获得这样的价值:

return MyEnum.type;

Try the following: 请尝试以下操作:

enumValues(enumType:any):number[] {
    return Object.keys(enumType).map(k => enumType[k]).filter(v => typeof v === "number")
}

enumString(enumType:any, enumValue:any):string {
    return enumType[enumValue];
}

您可以安全地切换到常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM