我在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)
这似乎很奇怪,因为它保证了字母是Enum。有什么办法解决这个问题吗?
我会把我的评论作为答案发布,这样问题就不会一直没有答案。
cipher
的类型将具有作为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
。