在Typescript中将整型转换为枚举字符串

90

我从一个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”时,我只得到一个整数值。但我想得到一个字符串值。

例如:

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

这是一个编译时问题还是运行时问题? - James Monger
它编译和运行得很好。对于{{message.type}},我得到了0,但我想要得到Info - Franz Peter Tebartz van Elst
4个回答

127

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

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

Type[0] // "Info"

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

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

文档


我该怎么做?我现在正在这样映射:(response => response.json() as Message[] - Franz Peter Tebartz van Elst
2
Type导入到您的文件中,而不是使用message.type来获取值,使用Type[message.type]来进行操作。您可以在需要字符串值的地方进行这样的操作。 - James Monger
7
不幸的是,在模板中 Type 无法直接使用,除非你将其作为组件类的一个属性添加进来,例如 public Type = Type; - user663031
1
有人能告诉我为什么在我的代码中,如果我使用Type[message.type],在调试器中会出现错误,因为Type未定义(它已经正确导入到这个.ts文件中)? - Vodenjak

63

TypeScript中的枚举是在运行时具有从int -> string和从string -> int的属性的对象,适用于所有可能的值。

要访问字符串值,您需要调用:

Type[0] // "Info"

请确保将正确的类型传递到属性访问器中,因为链式调用可能会导致以下结果:

Type[Type.Info] // "Info"
Type[Type[Type.Info]] // 0
Type["Info"] // 0
Type[0] // "Info"

如何检查一个数字是否是枚举的一部分,例如在返回Type [3000]之前检查数字3000? - gajo357
1
@gajo357 您可以使用 in 运算符来测试 3000 或任何值/键是否存在于枚举中。例如 const has3000 = 3000 in Type - Teddy Sterne

3

这是 TypeScript 中枚举的工作原理:

   enum PrintMedia {
      Newspaper = 1,
      Newsletter,
      Magazine,
      Book
    }

  PrintMedia.Magazine;            // returns  3
  PrintMedia["Magazine"];         // returns  3
  PrintMedia[3];                  // returns  Magazine
  PrintMedia[PrintMedia.Magazine];// returns  Magazine

2

I think with

{{message.type}}

您只需获取映射值而不是枚举值。 请尝试以下代码。

{{TYPE[message.type]}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接