TypeScript: how to properly iterate over a dictionary (object) in a loop?
Hi everyone! I just started learning TypeScript and encountered a task that seems simple but has me stumped. I have an object that I'm using as a dictionary (keys are strings, values are numbers). I need to iterate over all its key-value pairs in a loop. In regular JavaScript, I would do it like this:
```typescript
const dict = {
apple: 5,
banana: 3,
orange: 7
};
for (let key in dict) {
console.log(key, dict[key]);
}
```
But TypeScript complains about `dict[key]` — it says something about `Element implicitly has an 'any' type because index expression is not of type 'number'`. I tried using `Object.keys`:
```typescript
Object.keys(dict).forEach(key => {
console.log(key, dict[key]); // error again!
});
```
Also an error! How do I properly iterate over an object-dictionary in TypeScript?
No answers yet.
Log in to leave an answer