简体   繁体   English

TypeScript:获取const enum的成员名称作为字符串?

[英]TypeScript: Get member name of const enum as a string?

Suppose I have this const enum definition: 假设我有这个const枚举定义:

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

In my typescript code, can get the string literal of one of the members? 在我的打字稿代码中,可以获得其中一个成员的字符串文字吗?

In C# it would be eg nameof(Snack.Orange) . 在C#中,它将是例如nameof(Snack.Orange) (I know that nameof isn't supported by typescript and I known how it's possible for non-const enums.) (我知道打字稿不支持nameof,我知道非const枚举的可能性。)

By default const enums are completely removed at compile time, so there is no runtime object that represents the enum. 默认情况下,const枚举在编译时被完全删除,因此没有表示枚举的运行时对象。 You can use preserveConstEnums to force the enum object to be generated. 您可以使用preserveConstEnums强制生成枚举对象。 The problem is the compiler will still not allow you to access the enum object, so you have to use a work around to access the enum. 问题是编译器仍然不允许您访问枚举对象,因此您必须使用解决方法来访问枚举。

With preserveConstEnums turned on, we can put the enum in a namespace: 打开preserveConstEnums ,我们可以将枚举放在命名空间中:

namespace enums {
    export const enum Snack {
        Apple = 0,
        Banana = 1,
        Orange = 2,
        Other = 3
    }
}
let enumName = (enums as any).Snack[enums.Snack.Apple];

Or if the enum is within a module: 或者如果枚举在一个模块中:

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

let enumName = (exports as any).Snack[Snack.Apple];

If you don't want to use this flag, you can create an object that will by it's definition have to contain all the members of the enum, and you can search this object for the name. 如果您不想使用此标志,则可以创建一个对象,该对象将根据其定义包含枚举的所有成员,并且您可以在此对象中搜索该名称。 Given that you will get a compile time error on this object if you add or remove anything from the enum this might be a usable work around: 如果你在枚举中添加或删除任何东西,你会在这个对象上得到编译时错误,这可能是一个可用的解决方法:

let SnackNames : { [P in keyof typeof Snack]: { Name: P, Value: typeof Snack[P] } } = {
    Apple : { Value: Snack.Apple, Name: "Apple" },
    Banana : { Value: Snack.Banana, Name: "Banana" },
    Orange : { Value: Snack.Orange, Name: "Orange" },
    Other : { Value: Snack.Other, Name: "Other" },
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM