将 int 转换为 Typescript 中的枚举字符串

新手上路,请多包涵

我从 RESTful 服务获得以下数据:

 [
  {
    "id": 42,
    "type": 0,
    "name": "Piety was here",
    "description": "Bacon is tasty, tofu not, ain't nobody like me, cause i'm hot...",
  }...

我正在使用这个类进行映射:

 export enum Type {
  Info,
  Warning,
  Error,
  Fatal,
}

export class Message{
  public id: number;
  public type: Type:
  public name: string;
  public description: string;
}

但是当我在 Angular2 中访问“类型”时,我只得到一个 int 值。但我想得到一个字符串值。

例如:

 'message.type=0'
{{message.type}} => should be Info
'message.type=1'
{{message.type}} => should be Warning

原文由 Franz Peter Tebartz van Elst 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 528
1 个回答

Enums in TypeScript are numbers at runtime, so message.type will be 0 , 1 , 2 or 3 .

要获取字符串值,您需要将该数字作为索引传递到枚举中:

 Type[0] // "Info"

因此,在您的示例中,您需要这样做:

 Type[message.type] // "Info" when message.type is 0

文档

原文由 James Monger 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题