我从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中访问"type"时,我只得到一个int值.但我想得到一个字符串值.

例如:

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

推荐答案

TypeScript中的枚举在运行时是数字,所以message.type将是0123.

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

Type[0] // "Info"

所以,在你的例子中,你需要这样做:

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

Docs

Typescript相关问答推荐

如果在TypeScript中一个原始的类方法是递归的,如何使用类decorator 模式?

TypeScript泛型参数抛出错误—?&#"' 39;预期"

我应该使用什么类型的React表单onsubmit事件?

如何在排版中正确键入中间件链和控制器链

创建一个根据布尔参数返回类型的异步函数

在Reaction-Native-ReAnimated中不存在Animated.Value

如何创建一家Reduxstore ?

如何在方法中正确地传递来自TypeScrip对象的字段子集?

如何从MAT-FORM-FIELD-MAT-SELECT中移除焦点?

TypeScrip:使用Union ToInterval辅助对象,但保留子表达式

界面中数组中的混合类型导致打字错误

创建一个函数,该函数返回一个行为方式与传入函数相同的函数

如何在Next.js和Tailwind.css中更改悬停时的字体 colored颜色

TypeScript:方法获胜';t接受较窄类型作为参数

如何提取具有索引签名的类型中定义的键

如何键入';v型';

为什么我无法在 TypeScript 中重新分配函数?

使用react+ts通过props传递数据

如何编写一个接受 (string|number|null|undefined) 但只返回 string 且可能返回 null|undefined 的函数?

如何使用 TypeScript 接口中第一个属性的值定义第二个属性