迭代字符串枚举

肯特

我必须缺少一些东西,但是我发现了几种遍历Enum而不是在字符串枚举上迭代的方法。

给出以下枚举:

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

我要实现的目标:

我想迭代该字符串枚举,以便获取值(!)。我尝试过的

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

上面的代码的问题:

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

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

问题:

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

肯特

@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
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章