首页 > 解决方案 > 我可以在 Json 的关键位置使用枚举吗

问题描述

我正在使用打字稿 Nodejs(MEAN 堆栈)

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

一个示例枚举就像

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.jsjsontypescriptexpressenums

解决方案


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

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)

推荐阅读