Const enum in Typescript

I have a React application using Typescript. Right now I am facing a problem with const enum. Here is my listing:

export const enum Snack { Apple = 0, Banana = 1, Orange = 2, Other = 3 } 

The service I'm trying to match does not return a value, but the index of the item in the enumeration. So, for example, if a user is set to snack on an apple, the service returns 0 for that user instead of "Apple". Ideally, I would like to do something like:

 var snackIndex = UserSnack.type; // returning 0 in this example var userSnack = Snack[snackIndex]; // would return 'Apple' 

When I try something like this, I get the following error:

error TS2476: a const member of an enumeration can only be accessed using a string literal.

Since the service in which I receive the data does not return a string, I am having problems with its operation.

Any help is appreciated.

+6
source share
1 answer

const in the enumeration means that the enumeration is completely erased, which means that you cannot index it with an arbitrary value. Just remove the const modifier.

See also. How do different enumeration options work in TypeScript?

+13
source

Source: https://habr.com/ru/post/1011672/


All Articles