I have a string enum in TypeScript, and I want to iterate over it like below. However, when I do this the type of the iterator is a string instead of the enum type.
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'
}
The exact error I get is this:
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)
This seems strange as it's guaranteed the letter is an Enum. Is there any way to work around this?
cipherwill have the keys as theEnumvalues, that is{ a: string, b: string }because you are using a string enum, but when you are iterating with thefor ... inyou are iterating over the enumerable props of the generated object that is['A', 'B']because the object is generated asvar Enum; (function (Enum) { Enum["A"] = "a"; Enum["B"] = "b"; })(Enum || (Enum = {}));for ... ofandObject.valuesbecause the Enum is not directly iterable. final code:for (const letter of Object.values(Enum)) { cipher[letter] = 'test'; // error: letter is of type 'string' but needs to be 'Enum' }