Skip to content Skip to sidebar Skip to footer

Declare Key Type Of For In Loop In Typescript

I have below code const urlParams = new URLSearchParams(window.location.search); interface PersonType { fname: string lname: string } const person: PersonType = {fname:'Jo

Solution 1:

In TypeScript, for..in will only type the key being iterated over as a string - not as a key of the object being iterated over. Since key is typed as a string, not as newobj, you can't use newObj[key], because the generic string doesn't exist on the type.

Use Object.entries instead, to extract the key and the value at once, rather than trying to go through the key alone:

for(const [key, val] of Object.entries(newObj) {
    urlParams.append(key, val);
}

Post a Comment for "Declare Key Type Of For In Loop In Typescript"