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.
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. So from API and to API I have to send strings. But inside app I want to asap convert string from API to enum.
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.
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];
}
您可以安全地切换到常量。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.