是否有可能在Typescript迭代一个常量枚举?
问题描述:
与此question类似,但枚举标记为常量:你如何去从常量枚举中迭代或生成一个数组?是否有可能在Typescript迭代一个常量枚举?
例
declare const enum FanSpeed {
Off = 0,
Low,
Medium,
High
}
Desireable结果
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"}
];
答
没有,这是不可能用const enum
。让我们先从原来的枚举并记录其价值之一:
const enum FanSpeed {
Off = 0,
Low,
Medium,
High
}
console.log(FanSpeed.High);
打字稿编译器内联所有FanSpeed
引用,并编译上面的代码弄成这个样子:
console.log(3 /* High */);
换句话说,因为您使用const enum
,所以在运行时实际上不存在FanSpeed
对象,只是传递简单的数字文字。使用常规非常量enum
,FanSpeed
将作为值存在,您可以遍历其键。
编辑:如果你可以改变你的项目的编译器设置,请参阅Titian's answer below有关preserveConstEnums
标志非常有用的信息,这将导致一个FanSpeed
对象其实是可以创造的,因此给你一个方法来迭代您枚举。
答
您可以使用preserveConstEnums
编译器标志。这将在Javascript中发出枚举对象,但替换所有值。问题在于,您无法以简单的方式在属性上输入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.
)。有办法解决它,但这取决于你的环境。 使用的模块,你可以写这样的:
import * as e from "./enumModule"
for(var prop in (e as any)['FanSpeed']) {
console.log(prop) ;
}
或使用命名空间,你可以做这样的:
namespace Enums {
export const enum FanSpeed {
Off = 0,
Low,
Medium,
High
}
}
for(var prop in (Enums as any)['FanSpeed']) {
console.log(prop) ;
}
注:在这两种情况下,你必须首先使用preserveConstEnums编译器选项,
真的很感谢你对此的闪电反应!有用的见解! – Jim
是否可以使用preserveConstEnums编译器标志来保存常量枚举 –
是的,提到@ TitianCernicova-Dragomir非常重要。我链接到你的回答,我的答案,以便他们看到你写的关于'preserveConstEnums' – JKillian