我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
当前回答
我卑微的2美分基于阅读一个了不起的评论从github TS讨论
const EnvironmentVariants = ['development', 'production', 'test'] as const
type EPredefinedEnvironment = typeof EnvironmentVariants[number]
然后在编译时:
// TS2322: Type '"qaEnv"' is not assignable to type '"development" | "production" | "test"'.
const qaEnv: EPredefinedEnvironment = 'qa'
在运行时:
function isPredefinedEnvironemt(env: string) {
for (const predefined of EnvironmentVariants) {
if (predefined === env) {
return true
}
}
return false
}
assert(isPredefinedEnvironemet('test'), true)
assert(isPredefinedEnvironemet('qa'), false)
注意,for(const index in environmentvariables){…}将遍历"0","1","2"集合
其他回答
假设您坚持使用规则,只生成带有数值的枚举,您可以使用这段代码。这正确地处理了名称恰好是有效数字的情况
enum Color {
Red,
Green,
Blue,
"10" // wat
}
var names: string[] = [];
for(var n in Color) {
if(typeof Color[n] === 'number') names.push(n);
}
console.log(names); // ['Red', 'Green', 'Blue', '10']
简单地说
如果你的枚举如下:
export enum Colors1 {
Red = 1,
Green = 2,
Blue = 3
}
要获得特定的文本和值:
console.log(Colors1.Red); // 1
console.log(Colors1[Colors1.Red]); // Red
获取值和文本列表:
public getTextAndValues(e: { [s: number]: string }) {
for (const enumMember in e) {
if (parseInt(enumMember, 10) >= 0) {
console.log(e[enumMember]) // Value, such as 1,2,3
console.log(parseInt(enumMember, 10)) // Text, such as Red,Green,Blue
}
}
}
this.getTextAndValues(Colors1)
如果你的枚举如下:
export enum Colors2 {
Red = "Red",
Green = "Green",
Blue = "Blue"
}
要获得特定的文本和值:
console.log(Colors2.Red); // Red
console.log(Colors2["Red"]); // Red
获取值和文本列表:
public getTextAndValues(e: { [s: string]: string }) {
for (const enumMember in e) {
console.log(e[enumMember]);// Value, such as Red,Green,Blue
console.log(enumMember); // Text, such as Red,Green,Blue
}
}
this.getTextAndValues(Colors2)
如果你有enum
enum Diet {
KETO = "Ketogenic",
ATKINS = "Atkins",
PALEO = "Paleo",
DGAF = "Whatever"
}
然后你可以得到如下的键和值:
Object.keys(Diet).forEach((d: Diet) => {
console.log(d); // KETO
console.log(Diet[d]) // Ketogenic
});
可以是简短的:
enum AnimalEnum {
DOG = "dog",
CAT = "cat",
MOUSE = "mouse"
}
Object.keys(AnimalEnum).filter(v => typeof v == 'string' && isNaN(v))
老问题了,为什么不使用const对象映射呢?
不要这样做:
enum Foo {
BAR = 60,
EVERYTHING_IS_TERRIBLE = 80
}
console.log(Object.keys(Foo))
// -> ["60", "80", "BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE", 60, 80]
这样做(注意as const强制转换):
const Foo = {
BAR: 60,
EVERYTHING_IS_TERRIBLE: 80
} as const
console.log(Object.keys(Foo))
// -> ["BAR", "EVERYTHING_IS_TERRIBLE"]
console.log(Object.values(Foo))
// -> [60, 80]