我在 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
将具有Enum
值作为密钥,即{ a: string, b: string }
,因为您正在使用字符串枚举,但是当您使用for ... in
进行迭代时,您正在迭代生成的对象的可枚举属性,即['A', 'B']
,因为该对象被生成为var Enum; (function (Enum) { Enum["A"] = "a"; Enum["B"] = "b"; })(Enum || (Enum = {}));
。 - robertgr991for ... of
和Object.values
迭代对象的值,因为枚举本身不可迭代。 最终代码:for (const letter of Object.values(Enum)) { cipher[letter] = 'test'; // 错误:letter 的类型为 'string',但需要 'Enum' }
- robertgr991