【问题标题】:Cast int to enum strings in Typescript将 int 转换为 Typescript 中的枚举字符串
【发布时间】:2017-07-07 01:23:39
【问题描述】:

我从 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

【问题讨论】:

  • 这是编译时问题还是运行时问题?
  • 它编译并运行良好。对于{{message.type}],我得到0,但我想得到Info。

标签: javascript angular typescript enums


【解决方案1】:

TypeScript 中的枚举是运行时的数字,因此 message.type 将是 0、1、2 或 3。

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

Type[0] // "Info"

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

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

Docs

【讨论】:

  • 我该怎么做?我现在正在这样映射:(response => response.json() as Message[]
  • 将Type 导入到您的文件中,而不是使用message.type 来获取值,而是使用Type[message.type]。您在需要字符串值的地方执行此操作
  • 不幸的是,Type 在模板中不可用,除非您将其作为属性添加到组件类中,如 public Type = Type;。
  • 谁能告诉我为什么如果我在我的情况下使用 Type[message.type],在调试器中我会看到一个错误,因为 Type 未定义(它已正确导入到此 .ts 文件中)?
【解决方案2】:

我认为

{{message.type}}

你只得到映射的值而不是枚举。 请尝试以下代码。

{{TYPE[message.type]}}

【讨论】:

    【解决方案3】:

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

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

    Type[0] // "Info"
    

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

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

    【讨论】:

    • 如何检查一个数字是否是枚举的一部分,f.x。在返回 Type[3000] 之前检查数字 3000?
    • @gajo357 您可以使用in 运算符来测试枚举中是否存在 3000 或任何值/键。示例const has3000 = 3000 in Type
    猜你喜欢
    • 2019-03-10
    • 2018-06-21
    • 2020-10-30
    • 2018-07-07
    • 2013-06-27
    • 2021-04-11
    • 2010-10-03
    相关资源
    最近更新 更多