Skip to content
Advertisement

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:

JavaScript

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:

JavaScript

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.

Advertisement

Answer

Just remove the const modifier.

const in an enum means the enum is fully erased during compilation. Const enum members are inlined at use sites. You can can’t index it by an arbitrary value. In other words, the following TypeScript code

JavaScript

is compiled to:

JavaScript

Compare it with non-const version:

JavaScript

it is compiled to:

JavaScript

Source: const enums @ typescriptlang.org

Advertisement