Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: string enum return undefined

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.

like image 807
Sasugasm Avatar asked Dec 21 '18 13:12

Sasugasm


People also ask

Can enum be undefined?

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).

How do I convert a string to enum in TypeScript?

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.

Are TypeScript enums bad?

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.

Can an enum be a string?

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.


1 Answers

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
}
like image 93
Daniel Hilgarth Avatar answered Oct 12 '22 21:10

Daniel Hilgarth