N
N
Nikita2020-07-09 02:25:03
typescript
Nikita, 2020-07-09 02:25:03

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();
}


Error log tsc:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IObject '.
No index signature with a parameter of type 'string' was found on type 'IObject '.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Loli E1ON, 2020-07-09
@MiiZZo

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 question

Ask a Question

731 491 924 answers to any question