Issue
I have this class, which is supposed to represent an enum:
export default class ChangeStatusEnum {
"added" = "added";
"deleted" = "deleted";
"edited" = "edited";
"unedited" = "unedited";
static constructFromObject(object) {
return object;
}
}
It is generated in the pipeline by openapi-generator1 so changing it is not an option. This is not a question on best practices for defining enums in vanilla-js or typescript, this question is about how to use this class.
I do not understand the syntax of assigning to a string, I do not know where these four strings are accessible.
Here are a few things that I have tried (in a jenkins-test so they can be run easily):
test("access", () => {
console.log(ChangeStatusEnum) // prints [class ChangeStatusEnum]
console.log(JSON.stringify(ChangeStatusEnum)) // prints undefined
console.log(
ChangeStatusEnum.constructFromObject("deleted") === "deleted"
) // prints true
console.log(
ChangeStatusEnum.constructFromObject("nonexisting") === "nonexisting"
) // also prints true, which means this syntax has no value over just using strings instead of enums
console.log(ChangeStatusEnum["added"]) // prints undefined
console.log(ChangeStatusEnum.added) // prints undefined
})
The least I expect from a datastructure that calls itself "enum" is that I can construct and compare values of it without fear of silently constructing non-existing values. Iterating over all values of an enum would also be nice, but is not strictly necessary. I suppose there is a way to do that with this datastructure that I just do not know of due to lack of knowledge of advanced javascript-constructs.
1 The tool is openapi-generator-cli in version 2.5.1 https://www.npmjs.com/package/@openapitools/openapi-generator-cli with openapi-generator-maven-plugin version 6.0.0 https://mvnrepository.com/artifact/org.openapitools/openapi-generator-maven-plugin Since this is somewhat mature tooling I expect their enum-solution to be usable, this is why I ask this question as a js-question and not as an openapi-question.
Solution
I think the most elegant way to use it is to create an instance of it and use it as a constant. The 'constructFromObject'-function is not needed for this. So just put this below the imports:
const changeStatusEnum = new ChangeStatusEnum();
Afterwards, the members can be accessed using normal dot notation:
changeStatusEnum.added // evaluates to the string "added"
Answered By - julaine
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.