I have an enum defined like this :
export enum ViewSide {
Left = 'left',
Right = 'right'
}
But when I try to use it, it doesn't work as intended:
console.log(ViewSide); // return {0: "LEFT", 1: "RIGHT", LEFT: 0, RIGHT: 1}
console.log(ViewSide.Right); // return undefined instead of 'right'
console.log(ViewSide['Right']); // return undefined
I have used similar enums, but they works correctly and return the string.
Any idea ?
EDIT: Turns out it was just a cache problem. I had defined the enum without the string before, and it stayed like this for a while.
The enum error - cannot read property of undefined occurs for 2 main reasons: Using const enums that get removed during compilation. Having circular imports (importing members between the same files).
To convert a string to an enum: Use keyof typeof to cast the string to the type of the enum. Use bracket notation to access the corresponding value of the string in the enum.
The they are useless at runtime argument This is a false argument for typescript in general, let alone Enums. and agree, if at runtime some code tries to change the values of one of your enums, that would not throw an error and your app could start behaving unexpectedly ( that is why Object.
In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member. While string enums don't have auto-incrementing behavior, string enums have the benefit that they “serialize” well.
The only explanation is that you have two enums with the same name and have imported the wrong one.
As you can see from the first console.log
output, the other enum is defined like this:
export enum ViewSide {
LEFT,
RIGHT
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With