繁体   English   中英

在 Typescript 中转换为枚举字符串

[英]Cast int to enum strings in 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...",
  }...

我正在映射这个 class:

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

在打字稿枚举是在运行时数,所以message.type0123

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

Type[0] // "Info"

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

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

文件

TypeScript中的枚举是运行时的对象,这些对象具有从int -> stringstring -> int到所有可能值的属性。

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

Type[0] // "Info"

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

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

我想

{{message.type}}

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

{{TYPE[message.type]}}

这是枚举在 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

暂无
暂无

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

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