Typescript中的const枚举 [英] const enum in Typescript
问题描述
我有一个使用Typescript的React应用程序。现在,我遇到了const枚举的问题。这是我的枚举:
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
}
服务我试图匹配的不是返回值,而是枚举中该项的索引。因此,例如,如果用户设置为在苹果上吃零食,则该服务将为该用户返回0,而不是 Apple。理想情况下,我想执行以下操作:
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:
错误TS2476:只能使用字符串文字访问const枚举成员。
由于我从中接收数据的服务未返回字符串,因此在使该功能正常工作时遇到了问题。
Since the service I'm receiving the data from doesn't return the string, I'm having issues getting this working.
我们将不胜感激。
推荐答案
const
表示枚举已被完全擦除,这意味着您不能通过任意值对其进行索引。只需删除 const
修饰符即可。
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.
这篇关于Typescript中的const枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!