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

Fra*_*lst 32 javascript enums typescript angular

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

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

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

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


export class Message{
  public id: number;
  public type: Type:
  public name: string;
  public description: string;
}
Run Code Online (Sandbox Code Playgroud)

但是当我在Angular2中访问'type'时,我只得到一个int值.但是我想获得一个字符串值.

例如:

'message.type=0'
{{message.type}} => should be Info
'message.type=1'
{{message.type}} => should be Warning
Run Code Online (Sandbox Code Playgroud)

Jam*_*ger 45

在打字稿枚举是在运行时的数字,所以message.type0,1,23.

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

Type[0] // "Info"
Run Code Online (Sandbox Code Playgroud)

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

Type[message.type] // "Info" when message.type is 0
Run Code Online (Sandbox Code Playgroud)

文件

  • 不幸的是,`Type`在模板中不可用,除非你把它作为属性添加到组件类中,作为`public Type = Type;`. (5认同)
  • 将 `Type` 导入到您的文件中,而不是执行 `message.type` 来获取值,而是执行 `Type[message.type]`。您可以在需要字符串值的地方执行此操作 (2认同)

Ted*_*rne 31

TypeScript中的枚举是运行时的对象,具有来自int -> string和来自string -> int所有可能值的属性.

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

Type[0] // "Info"
Run Code Online (Sandbox Code Playgroud)

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

Type[Type.Info] // "Info"
Type[Type[Type.Info]] // 0
Type["Info"] // 0
Type[0] // "Info"
Run Code Online (Sandbox Code Playgroud)