迭代字符串枚举

ken*_*tor 8 node.js typescript

我一定遗漏了一些东西,但我找到了几种方法来遍历枚举而不是字符串枚举。

给出了以下枚举:

export enum Locales {
  En = 'en',
  Fr = 'fr',
  De = 'de',
  Es = 'es',
  It = 'it',
  Nl = 'nl',
  No = 'no',
  Tr = 'tr',
}
Run Code Online (Sandbox Code Playgroud)

我想要达到的目标:

我想迭代那个字符串枚举,以便我得到值(!)。我试过的:

for (const key of Object.keys(Locales)) {
  const locale: string = Locales[key];
  console.log(locale); // Should print 'en', 'fr' and so on
}
Run Code Online (Sandbox Code Playgroud)

上面代码的问题:

由于严格的 tsconfig(不允许隐式 anys),我无法将其编译为 javascript。由于这不是我的项目,因此我也无法更改此 tsconfig。它突出显示了key变量 atLocales[key]并且错误对我来说很有意义:

[ts] 元素隐式具有“any”类型,因为索引表达式不是“number”类型。

问题:

使用 Typescript 2.6+ 迭代字符串枚举以获取其值的正确方法是什么?

art*_*tem 11

正如 betadeveloper 所建议的,如果您使用 type assertion ,您可以获得正确的 key 类型as keyof typeof Locales。或者您可以将其包装在类型安全的Object.keys()函数变体中,如下所示:

export enum Locales {
  En = 'en',
  Fr = 'fr',
  De = 'de',
  Es = 'es',
  It = 'it',
  Nl = 'nl',
  No = 'no',
  Tr = 'tr',
}

function enumKeys<E>(e: E): (keyof E)[] {
  return Object.keys(e) as (keyof E)[];
}

for (const key of enumKeys(Locales)) {
  const locale: string = Locales[key];
  console.log(locale); 
}
Run Code Online (Sandbox Code Playgroud)

此外,为了记录,旧式for .. in循环仍然有效:

for (let key in Locales) {
    let locale = Locales[key];
    console.log(locale);
}
Run Code Online (Sandbox Code Playgroud)

  • `keyof typeof Locales` 有效,`keyof Locales` 无效。 (2认同)

ken*_*tor 8

@Artem 和 @betadeveloper 指出我可以在keyof typeof Locales我的方法中使用该类型。我最终想出的解决方案如下所示:

const keys: (keyof typeof Locales)[] = <(keyof typeof Locales)[]>Object.keys(Locales);
for (const key of keys) {
  const locale: string = Locales[key];
  console.log(locale); // Prints 'en', 'fr' and so on
}
Run Code Online (Sandbox Code Playgroud)