Reputation: 113
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?
Upvotes: 4
Views: 2856
Reputation: 2586
I will often just redeclare the key with an explicit type. Especially, if I use the key often inside the loop.
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 keyTemp in person) {
const key = keyTemp as keyof PersonType; // key redeclared with type
urlParams.append(key, newObj[key]);
}
Upvotes: 0
Reputation: 1
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 as keyof PersonType]);
}
in newObj[key]
add as keyof PersonType
Upvotes: 0
Reputation: 370769
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);
}
Upvotes: 5