Node Version: 6.11.3
Typescript Version: 2.1.6
We have a bunch of enums in our project that mostly look like this:
export type ThingType = "thing1" | "thing2";
export namespace ThingType {
export const THING_ONE = "thing1";
export const THING_TWO = "thing2";
}
I want to expose these values in an endpoint for consumers of the endpoints that require these string values. So I've made an endpoint that looks like this:
const enums = {
thingType: ThingType,
...
}
Which returns json looking like:
"data": {
"thingType": {
"THING_ONE": "thing1",
"THING_TWO": "thing2"
}
}
I want it to be output like:
"data": {
"thingType": ["thing1", "thing2"]
}
For a plain javascript object, that would be fairly easy, I'd just add values()
to the end of ThingType
in my endpoint. But values()
does not exist on namespaces or enums in TS. I haven't found anything in the docs on namespaces in Typescript but I feel there's gotta be something that would let me get the enum values easily.
Node Version: 6.11.3
Typescript Version: 2.1.6
We have a bunch of enums in our project that mostly look like this:
export type ThingType = "thing1" | "thing2";
export namespace ThingType {
export const THING_ONE = "thing1";
export const THING_TWO = "thing2";
}
I want to expose these values in an endpoint for consumers of the endpoints that require these string values. So I've made an endpoint that looks like this:
const enums = {
thingType: ThingType,
...
}
Which returns json looking like:
"data": {
"thingType": {
"THING_ONE": "thing1",
"THING_TWO": "thing2"
}
}
I want it to be output like:
"data": {
"thingType": ["thing1", "thing2"]
}
For a plain javascript object, that would be fairly easy, I'd just add values()
to the end of ThingType
in my endpoint. But values()
does not exist on namespaces or enums in TS. I haven't found anything in the docs on namespaces in Typescript but I feel there's gotta be something that would let me get the enum values easily.
1 Answer
Reset to default 6Namespaces are piled into plain javacsript objects, so Object.values() works as expected (in the environment that supports Object.values
of course):
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);
shows
{ thingType: ['thing1', 'thing2'] }
If Object.values
is not available it gets a little more verbose:
const enums = {
thingType: Object.keys(ThingType).map(k => ThingType[k])
}