Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:"John", lname:"Doe"};

const newObj = {
    newobj: "new value"
}

for(const key in person) {
    urlParams.append(key, newObj[key]); //error
}

https://codesandbox.io/s/vanilla-ts?utm_source=dotnew&file=/src/index.ts:0-500

how should I declare's key string in the for in loop?

like image 514
Judy Allen Avatar asked Oct 24 '25 02:10

Judy Allen


1 Answers

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);
}
like image 128
CertainPerformance Avatar answered Oct 25 '25 17:10

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!