简体   繁体   English

在打字稿中映射枚举

[英]Mapping enum in typescript

What is the proper way to map enum in typescript? 在打字稿中映射枚举的正确方法是什么?

For instance I am playing around with an online typescript code editor and this works fine: 例如,我正在玩一个在线打字稿代码编辑器,这很好用:

class Message
{
    name: string;
    min: number;
    max: number;
    messageType: MessageType;
}

enum MessageType
{
    none,
    email,
    sms

}

var jsonObj = {
    "name": "some name",
    "min": 0,
    "max": 10,
    "messageType": MessageType.email

}

var messageInstance: Message = <Message>jsonObj;

console.log(messageInstance);

However, in my IDE MessageType.email shows an error of "value expected" if I use it in a json file. 但是,在我的IDE中,如果我在json文件中使用它, MessageType.email显示“value expected”错误。

If I try: 如果我尝试:

"messageType": "MessageType.email"

In the online code editor then that generates an error. 在在线代码编辑器中,然后生成错误。

I am just getting started and can't find any clear instructions on how this should be done. 我刚刚开始,无法找到有关如何完成此操作的明确说明。

edit: 编辑:

I just realised enums are number based so "messageType": 2 or whatever corresponding number would be the correct way to go. 我刚刚意识到枚举是基于数字所以"messageType": 2或任何相应的数字将是正确的方法去。

Is there any way to make the enum readable in the json file (ie something like MessageType.email as a value) as when viewed alone the json file doesn't have the enum definitions so might be confusing so I'd rather do it that way if possible.. 有没有办法让json文件中的枚举可读(比如像MessageType.email这样的值),因为单独查看时json文件没有枚举定义所以可能会让人感到困惑,所以我宁愿这样做方式如果可能..

For TypeScript 2.4+: 对于TypeScript 2.4+:

You can use string enums instead of a numeric enum: 您可以使用字符串枚举而不是数字枚举:

enum MessageType
{
    none = "none",
    email = "email",
    sms = "sms"
}

For older versions of TypeScript: 对于旧版本的TypeScript:

You can convert an enum value to a string using the enum 's indexer: 您可以使用enum的索引器将enum值转换为string

const messageTypeAsString = MessageType[MessageType.email];

Going the other way works too: 走另一条路也是有效的:

const messageType: MessageType = MessageType[messageTypeAsString];

As far as I know there is no way to automate this conversion when serializing/deserializing JSON. 据我所知,在序列化/反序列化JSON时无法自动执行此转换。

The other option is to skip enum entirely and use static string s instead: 另一种选择是完全跳过enum并使用静态string s:

class MessageType {
    static readonly none = 'none';
    static readonly email = 'email';
    static readonly sms = 'sms';
}
type MessageTypeValue = 'none' | 'email' | 'sms'; 

const messageType: MessageTypeValue = MessageType.none;

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

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