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

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

当前回答

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

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"]

其他回答

在当前的TypeScript版本1.8.9中,我使用类型化enum:

export enum Option {
    OPTION1 = <any>'this is option 1',
    OPTION2 = <any>'this is option 2'
}

与结果在这个Javascript对象:

Option = {
    "OPTION1": "this is option 1",
    "OPTION2": "this is option 2",
    "this is option 1": "OPTION1",
    "this is option 2": "OPTION2"
}

所以我必须通过键和值查询,只返回值:

let optionNames: Array<any> = [];    
for (let enumValue in Option) {
    let optionNameLength = optionNames.length;

    if (optionNameLength === 0) {
        this.optionNames.push([enumValue, Option[enumValue]]);
    } else {
        if (this.optionNames[optionNameLength - 1][1] !== enumValue) {
            this.optionNames.push([enumValue, Option[enumValue]]);
        }
    }
}

我在数组中收到选项键:

optionNames = [ "OPTION1", "OPTION2" ];

在TypeScript中,一个enum在javascript中被编译成一个map(从键中获取值):

enum MyEnum {
  entry0,
  entry1,
}

console.log(MyEnum['entry0']); // 0
console.log(MyEnum['entry1']); // 1

它还创建了一个反向映射(从值中获取键):

console.log(MyEnum[0]); // 'entry0'
console.log(MyEnum[0]); // 'entry1'

所以你可以通过以下方式访问一个条目的名称:

console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'

但是,string enum在设计上没有反向映射(参见注释和pull request),因为这可能导致映射对象中的键和值之间的冲突。

enum MyEnum {
  entry0 = 'value0',
  entry1 = 'value1',
}

console.log(MyEnum['value0']); // undefined
console.log(MyEnum['value1']); // undefined

如果你想强制你的字符串enum编译一个反向映射(你必须确保所有的键和值都是不同的),你可以使用这个技巧:

enum MyEnum {
  entry0 = <any>'value0',
  entry1 = <any>'value1',
}

console.log(MyEnum['value0']); // 'entry0'
console.log(MyEnum['value1']); // 'entry1'
console.log(MyEnum[MyEnum.entry0]); // 'entry0'
console.log(MyEnum[MyEnum.entry1]); // 'entry1'

从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;
};

可以是简短的:

enum AnimalEnum {
  DOG = "dog", 
  CAT = "cat", 
  MOUSE = "mouse"
}

Object.keys(AnimalEnum).filter(v => typeof v == 'string' && isNaN(v))

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