【问题标题】:Can I use enums at key position of Json我可以在 Json 的关键位置使用枚举吗
【发布时间】:2021-04-12 02:49:16
【问题描述】:

我正在使用 typescript Nodejs(MEAN 堆栈)

尝试在 json 的属性/模式中使用 enum

一个示例枚举就像

Enum KeyEnums {
  A: "featureA",
  B: "featureB",
  C: "featureC"
}

预期的 JSON

{
  featureA: "This is feature A",
  featureB: "This is feature C",
  featureC: "This is feature C"
}

我想要达到的方式

{
  KeyEnums.A: "This is feature A",
  KeyEnums.B: "This is feature C",
  KeyEnums.C: "This is feature C"
}

但是,得到一个错误提示

"Property or signature expected"

..无论如何要在 JSON 属性的地方实现枚举的使用?

【问题讨论】:

标签: node.js json typescript express enums


【解决方案1】:

您应该像这样用[] 包装枚举键:

enum KeyEnums {
  A = "featureA",
  B = "featureB",
  C = "featureC"
}

const a= {
  [KeyEnums.A]: "This is feature A",
  [KeyEnums.B]: "This is feature C",
  [KeyEnums.C]: "This is feature C"
}

const json = JSON.stringify(a)
console.log(json)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    相关资源
    最近更新 更多