节点版本:6.11.3
typescript 版本:2.1.6
我们的项目中有很多枚举,大部分看起来像这样:
export type ThingType = "thing1" | "thing2";
export namespace ThingType {
export const THING_ONE = "thing1";
export const THING_TWO = "thing2";
}
我想在端点中向需要这些字符串值的端点的使用者公开这些值。所以我创建了一个如下所示的端点:
const enums = {
thingType: ThingType,
...
}
返回的 json 看起来像:
"data": {
"thingType": {
"THING_ONE": "thing1",
"THING_TWO": "thing2"
}
}
我希望它的输出如下:
"data": {
"thingType": ["thing1", "thing2"]
}
对于普通的 javascript 对象,这相当简单,我只需将 values()
添加到端点中的 ThingType
末尾即可。但是 TS 中的命名空间或枚举上不存在 values()
。我在 docs on namespaces in Typescript 中没有找到任何内容但我觉得必须有一些东西可以让我轻松获得枚举值。
最佳答案
命名空间被编译成普通的 javacsript 对象,因此 Object.values()按预期工作(当然是在支持 Object.values
的环境中):
export type ThingType = "thing1" | "thing2";
export namespace ThingType {
export const THING_ONE = "thing1";
export const THING_TWO = "thing2";
}
const enums = {
thingType: Object.values(ThingType)
}
console.(enums);
显示
{ thingType: ['thing1', 'thing2'] }
如果Object.values
不可用,它会变得更加冗长:
const enums = {
thingType: Object.keys(ThingType).map(k => ThingType[k])
}
关于javascript - 获取 Typescript 中命名空间的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857479/