我在 TypeScript 中有一个字符串枚举,我想像下面这样迭代它。但是,当我这样做时,迭代器的类型是字符串而不是枚举类型。
enum Enum { A = 'a', B = 'b' };
let cipher: { [key in Enum]: string };
for (const letter in Enum) {
cipher[letter] = 'test'; // error: letter is of type 'string' but needs to be 'Enum'
}
我得到的确切错误是:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: string; b: string; }'.
No index signature with a parameter of type 'string' was found on type '{ a: string; b: string; }'.ts(7053)
这看起来很奇怪,因为它保证字母是枚举。有什么办法可以解决这个问题吗?
最佳答案
我会将我的评论作为答案发布,这样问题就不会无人问津。
cipher
的类型将 key 作为Enum
的值,即:
let cipher: {
a: string;
b: string;
}
因为您使用的是字符串枚举。但是当使用 for...in
迭代时,您迭代生成对象的可枚举属性,这些属性是 ['A', 'B']
因为生成的对象(TypeScript v4) 将是:
var Enum;
(function (Enum) {
Enum["A"] = "a";
Enum["B"] = "b";
})(Enum || (Enum = {}));
因此您需要迭代枚举值。
为此,您可以使用 Object.values
获取其值的数组,并使用 for...of
对其进行迭代。这样,letter
类型将是 Enum
。
for (const letter of Object.values(Enum)) {
cipher[letter] = 'test'; // error: letter is of type 'string' but needs to be 'Enum'
}
我以前从未将 for...in
与枚举一起使用,但我希望编译器有足够的信息,所以 for...in
严格类型 letter
到 "A"| 的并集"B"
但它似乎将类型扩展为 string
。
关于TypeScript 使用枚举类型而不是字符串类型迭代字符串枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67029237/