[英]Is it possible in Typescript to iterate over a const enum?
Similar to this question , but with the enumeration marked as a constant: How do you go about iterating or producing an array of from the const enum? 与此问题类似,但枚举标记为常量:如何从const枚举中迭代或生成数组?
Example 例
declare const enum FanSpeed {
Off = 0,
Low,
Medium,
High
}
Desireable Results 可取的结果
type enumItem = {index: number, value: string};
let result: Array<enumItem> = [
{index: 0, value: "Off"},
{index: 1, value: "Low"},
{index: 2, value: "Medium"},
{index: 3, value: "High"}
];
No, this is not possible with a const enum
. 不,使用const enum
是不可能的。 Let's start with your original enum and log one of its values: 让我们从您的原始枚举开始并记录其中一个值:
const enum FanSpeed {
Off = 0,
Low,
Medium,
High
}
console.log(FanSpeed.High);
The TypeScript compiler inlines all the references to FanSpeed
, and compiles the above code into something like this: TypeScript编译器内联对FanSpeed
所有引用,并将上面的代码编译成如下代码:
console.log(3 /* High */);
In other words, since you're using a const enum
, no FanSpeed
object actually exists at run time, just simple numeric literals are passed around instead. 换句话说,由于您正在使用const enum
,因此在运行时实际上不存在FanSpeed
对象,而是仅传递简单的数字文字。 With a regular, non-const enum
, a FanSpeed
would exist as a value and you could iterate over its keys. 使用常规的非const enum
, FanSpeed
将作为值存在,您可以迭代其键。
Edit : If you can change the compiler settings of your project, see Titian's answer below for very useful information about the preserveConstEnums
flag, which will cause a FanSpeed
object to actually be created and thus give you a way to iterate over your enum. 编辑 :如果您可以更改项目的编译器设置,请参阅下面的Titian答案,以获取有关preserveConstEnums
标志的非常有用的信息,这将导致实际创建FanSpeed
对象,从而为您提供迭代枚举的方法。
You can use the preserveConstEnums
compiler flag. 您可以使用preserveConstEnums
编译器标志。 This will emit the enum object in the Javascript but replace all values. 这将在Javascript中发出枚举对象,但替换所有值。 The problem is that you can't for
over the properties in a simple way because Typescript generates an error ( enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment.
). 问题是您不能for
简单的方式覆盖属性,因为Typescript会生成错误( enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment.
)。 There are ways to get around it but it depends on your environment. 有办法解决它,但这取决于你的环境。 Using modules you could write it like this: 使用模块你可以像这样写:
import * as e from "./enumModule"
for(var prop in (e as any)['FanSpeed']) {
console.log(prop) ;
}
Or using a namespace you could do it like this: 或者使用命名空间,你可以这样做:
namespace Enums {
export const enum FanSpeed {
Off = 0,
Low,
Medium,
High
}
}
for(var prop in (Enums as any)['FanSpeed']) {
console.log(prop) ;
}
Note: In either case you must use the preserveConstEnums compiler option first, 注意:在任何一种情况下,您必须首先使用preserveConstEnums编译器选项,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.