Answer the question
In order to leave comments, you need to log in
Why does typescript define the type of the key as string when iterating over the keys of an object using a for loop?
const object: IObject = {
number: 0
}
for (let key in object) {
object[key] = Math.random();
}
Answer the question
In order to leave comments, you need to log in
Well, yes, it's a string. You need to instantiate key so that it contains the keys of the iterated object:
const object: IObject = {
number: 0,
superNumber: 0,
}
let key: keyof IObject; // "number" | "superNumber"
for (key in object) {
object[key] = Math.random();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question