我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}

for (var entry in myEnum) { 
    // use entry's name here, e.g., "entry1"
}

当前回答

这个解决方案也可以。

enum ScreenType {
    Edit = 1,
    New = 2,
    View = 4
}

var type: ScreenType = ScreenType.Edit;

console.log(ScreenType[type]); //Edit

其他回答

如果你有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
});

从TypeScript 2.4开始,枚举不再包含键作为成员。来源TypeScript自述文件

需要注意的是,字符串初始化的枚举不能反向映射到原始枚举成员名。换句话说,你不能写Colors["RED"]来获得字符串"RED"。

我的解决方案:

export const getColourKey = (value: string ) => {
    let colourKey = '';
    for (const key in ColourEnum) {
        if (value === ColourEnum[key]) {
            colourKey = key;
            break;
        }
    }
    return colourKey;
};

基于上面的一些回答,我提出了这个类型安全的函数签名:

export function getStringValuesFromEnum<T>(myEnum: T): (keyof T)[] {
  return Object.keys(myEnum).filter(k => typeof (myEnum as any)[k] === 'number') as any;
}

用法:

enum myEnum { entry1, entry2 };
const stringVals = getStringValuesFromEnum(myEnum);

stringVals的类型是'entry1' | 'entry2'

看看它的实际应用

我写了一个helper函数来枚举一个枚举:

static getEnumValues<T extends number>(enumType: {}): T[] {
  const values: T[] = [];
  const keys = Object.keys(enumType);
  for (const key of keys.slice(0, keys.length / 2)) {
    values.push(<T>+key);
  }
  return values;
}

用法:

for (const enumValue of getEnumValues<myEnum>(myEnum)) {
  // do the thing
}

该函数返回可以轻松枚举的内容,并将其转换为枚举类型。

这里有很多答案,尽管这是一个7年前的问题,但我还是查了一下,我猜会有更多的答案出现在这里。这是我的解决方案,它比其他解决方案简单一点,它处理数字/文本/混合值枚举,都是一样的。

enum funky {
    yum , tum='tum', gum = 'jump', plum = 4
}

const list1 = Object.keys(funky)
  .filter(k => (Number(k).toString() === Number.NaN.toString()));
console.log(JSON.stringify(list1)); // ["yum","tum","gum","plum"]" 

 // for the numeric enum vals (like yum = 0, plum = 4), typescript adds val = key implicitly (0 = yum, 4 = plum)
 // hence we need to filter out such numeric keys (0 or 4)