Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

let snacks = [
  Snack.Apple,
  Snack.Banana,
  Snack.Orange,
  Snack.Other
];

is compiled to:

let Snacks = [
    0 /* Apple */,
    1 /* Banana */,
    2 /* Orange */,
    3 /* Other */
];

Compare it with non-const version:

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

let Snacks = [
  Snack.Apple,
  Snack.Banana,
  Snack.Orange,
  Snack.Other
];

it is compiled to:

var Snack;
(function (Snack) {
    Snack[Snack["Apple"] = 0] = "Apple";
    Snack[Snack["Banana"] = 1] = "Banana";
    Snack[Snack["Orange"] = 2] = "Orange";
    Snack[Snack["Other"] = 3] = "Other";
})(Snack || (Snack = {}));
let Snacks = [
    Snack.Apple,
    Snack.Banana,
    Snack.Orange,
    Snack.Other
];

Source: const enums @ typescriptlang.org


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...