addam addam - 1 year ago 245
TypeScript Question

const enum in Typescript

I have a React application that is using Typescript. Right now I'm running into an issue with const enum. Here's my enum:

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

The service I'm trying to match up to isn't returning the value, but the index of the item within the enum. So, for instance, if the user is set to snack on an apple, the service is returning a 0 for that user instead of 'Apple'. Ideally, I'd 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 similar I'm getting the following error:

error TS2476: A const enum member can only be accessed using a string literal.

Since the service I'm receiving the data from doesn't return the string, I'm having issues getting this working.

Any help is appreciated.

Answer Source

const in an enum means the enum is fully erased, which means you can't index it by an arbitrary value. Just remove the const modifier.

See also How do the different enum variants work in TypeScript?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download