V
V
vertically-challenged2022-02-13 13:43:05
typescript
vertically-challenged, 2022-02-13 13:43:05

How to use a for...in loop with TypeScript?

This code gives a compilation error (error text below), why is this happening, and how to fix it?

The code:

const fields = {
  weather: "weather"
};

for (let key in fields) {
  console.log("fields[key]: ", fields[key]);
}


Error text:
The element is implicitly of type "any" because an expression of type "string" cannot be used to index type "{ weather: string; }".
No index signature found in type '{ weather: string; }' with type parameter 'string'.ts(7053)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Loli E1ON, 2022-02-13
@vertically-challenged

const fields = {
  weather: "weather"
};

let key: keyof typeof fields;
for (key in fields) {
  console.log("fields[key]: ", fields[key]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question