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

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

当前回答

这里发现的另一个有趣的解决方案是使用ES6 Map:

export enum Type {
  low,
  mid,
  high
}

export const TypeLabel = new Map<number, string>([
  [Type.low, 'Low Season'],
  [Type.mid, 'Mid Season'],
  [Type.high, 'High Season']
]);

USE

console.log(TypeLabel.get(Type.low)); // Low Season


TypeLabel.forEach((label, value) => {
  console.log(label, value);
});

// Low Season 0
// Mid Season 1
// High Season 2    

其他回答

我卑微的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"集合

假设您有一个枚举

export enum SCROLL_LABEL_OFFSET {
  SMALL = 48,
  REGULAR = 60,
  LARGE = 112
}

你想要创建一个基于枚举的类型而不仅仅是复制和粘贴。 你可以像这样使用枚举来创建你的类型:

export type ScrollLabelOffset = keyof typeof SCROLL_LABEL_OFFSET;

结果你会收到一个可能值为'SMALL' | 'REGULAR' | 'LARGE'的类型

当我遇到同样的问题时,你可以使用我写的enum-values包:

Git: enum-values

var names = EnumValues.getNames(myEnum);

我希望这个问题仍然有意义。我使用这样的函数:

function enumKeys(target: Record<string, number|string>): string[] {
  const allKeys: string[] = Object.keys(target);
  const parsedKeys: string[] = [];

  for (const key of allKeys) {
    const needToIgnore: boolean
      = target[target[key]]?.toString() === key && !isNaN(parseInt(key));

    if (!needToIgnore) {
      parsedKeys.push(key);
    }
  }

  return parsedKeys;
}

function enumValues(target: Record<string, number|string>): Array<string|number> {
  const keys: string[] = enumKeys(target);
  const values: Array<string|number> = [];

  for (const key of keys) {
    values.push(target[key]);
  }

  return values;
}

例子:

enum HttpStatus {
  OK,
  INTERNAL_ERROR,
  FORBIDDEN = 'FORBIDDEN',
  NOT_FOUND = 404,
  BAD_GATEWAY = 'bad-gateway'
}


console.log(enumKeys(HttpStatus));
// > ["OK", "INTERNAL_ERROR", "FORBIDDEN", "NOT_FOUND", "BAD_GATEWAY"] 

console.log(enumValues(HttpStatus));
// > [0, 1, "FORBIDDEN", 404, "bad-gateway"]

如果你只搜索名称,然后迭代使用:

Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];