我一定是遗漏了什么,但我找到了几种遍历枚举而不是字符串枚举的方法。
给出以下枚举:
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。它突出显示 Locales[key]
处的 key
变量,错误对我来说很有意义:
[ts] Element implicitly has an 'any' type because index expression is not of type 'number'.
问题:
使用 Typescript 2.6+ 遍历字符串枚举以获取其值的正确方法是什么?
最佳答案
正如 betadeveloper 所建议的,如果您使用类型断言 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);
}
另外,郑重声明,旧式 for .. in
循环仍然有效:
for (let key in Locales) {
let locale = Locales[key];
console.log(locale);
}
关于node.js - 迭代字符串枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47896885/