enum Stage {
STARTED = 1,
COMPLETED
}
const SystemState = {
Stage,
}
Is it possible to create a type by extracting the enum from the SystemState
object i.e.
type stageType -> 1 | 2 (corresponds to the integral values of the Stage enum)
I’ve tried keyof typeof SystemState['Stage']
but this creates a string union type instead: "STARTED" | "COMPLETED"
.
2
Answers
Try this. Type ValueOf maps each key of the enum to its value, and then unions those types together. So you can apply this utility type to your enum to get a union of its values:
Enums in Typescript are odd. From their syntax you would think they would behave similar to enums in other languages but when they’re transpiled they can produce some subtle bugs. Here is an article that talks about the possible issues: https://dev.to/ivanzm123/dont-use-enums-in-typescript-they-are-very-dangerous-57bh
This article also describes an alternative to enums which looks like this:
I hope this helps!