gpt4 book ai didi

javascript - Typescript for in 循环,遍历联合类型的对象或数组

转载 作者:行者123 更新时间:2023-12-01 16:26:03 54 4
gpt4 key购买 nike

我正在尝试在对象或数组的联合类型上使用 for in 循环,因为数组也是对象,它们的关键属性是索引。

const loopOver = (question: any[] | {[key: string]: any} ) => {
for (let key in question) { // error ts 7053
console.log(question[key])
}
};

结果出错

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'any[] | { [key: string]: any; }'.
No index signature with a parameter of type 'string' was found on type 'any[] | { [key: string]: any; }'.ts(7053)

但是一旦我删除联合类型并将其留给对象或数组,我就不会收到任何错误。

// okay
const loopOver = (question: {[key: string]: any} ) => {
for (let key in question) {
console.log(question[key])
}
};
// okay
const loopOver = (question: any[] ) => {
for (let key in question) {
console.log(question[key])
}
};

配置文件

{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

package.json 中的 ts 版本 ^3.8.3

最佳答案

数组应该用数字而不是字符串来索引。但是 for..in 迭代 strings - 你的 key 是一个字符串。在数组上查找属性时,将字符串键转换为数字以使其起作用。 (但是在查找对象上的属性时,由于对象使用了[key: string]: any,所以必须继续使用字符串查找)

const loopOver = (question: [] | {[key: string]: any} ) => {
for (let key in question) {
if (Array.isArray(question)) {
console.log(question[Number(key)])
} else {
console.log(question[key])
}
}
};

但是,从这段代码来看,您似乎根本不关心键(并且 for..in should not 无论如何都与数组一起使用)。您只关心值,那么使用 Object.values 怎么样?

const loopOver = (question: [] | {[key: string]: any} ) => {
for (const val of Object.values(question)) {
console.log(val)
}
};

关于javascript - Typescript for in 循环,遍历联合类型的对象或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61165488/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com