Typescript 中的常量枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40227401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:57:19  来源:igfitidea点击:

const enum in Typescript

javascripttypescriptenums

提问by addam

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

我有一个使用 Typescript 的 React 应用程序。现在我遇到了 const 枚举的问题。这是我的枚举:

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:

我试图匹配的服务不​​是返回值,而是枚举中项目的索引。因此,例如,如果用户设置为吃苹果零食,则该服务将为该用户返回 0 而不是“Apple”。理想情况下,我想做类似的事情:

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.

错误 TS2476:只能使用字符串文字访问 const 枚举成员。

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.

任何帮助表示赞赏。

回答by Ryan Cavanaugh

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

const在枚举中意味着枚举被完全擦除,这意味着您不能通过任意值对其进行索引。只需删除const修改器。

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

另请参阅TypeScript 中不同的枚举变体如何工作?