[英]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 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?我应该如何在 for in 循环中声明关键字符串?
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.在 TypeScript 中,
for..in
只会将被迭代的键键入为字符串- 而不是作为被迭代的 object 的键。 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.由于
key
被键入为字符串,而不是newobj
,因此您不能使用newObj[key]
,因为该类型上不存在通用字符串。
Use Object.entries
instead, to extract the key and the value at once, rather than trying to go through the key alone:改用
Object.entries
来一次提取键和值,而不是尝试仅通过键 go :
for(const [key, val] of Object.entries(newObj) {
urlParams.append(key, val);
}
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
在
newObj[key]
中添加as keyof PersonType
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.