javascript - Typescript for in 循环,遍历对象或数组的联合类型
问题描述
我正在尝试使用for in loop
对象或数组的过度联合类型,因为数组也是对象,它们的关键属性是索引。
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])
}
};
tsconfig
{
"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
迭代字符串- 你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无论如何都不应该与数组一起使用)。你只关心这些值,那么如何使用Object.values
呢?
const loopOver = (question: [] | {[key: string]: any} ) => {
for (const val of Object.values(question)) {
console.log(val)
}
};
推荐阅读
- angularjs - 当我使用 $locationProvider.html5Mode(true); 时,$window.location.href 刷新整个页面;
- sql - 如何使用匹配值使用 CSV 文件中的数据更新 Postgres 中的列
- anaconda - Anaconda 安装错误
- javascript - 有没有办法将数据流式传输到一个 blob(或生成一个巨大的 blob)
- ios - 使用键从 2 个 JSON 对象创建单个 JSON 字符串
- windows - SSMS 17.5当单元格数据大于可用显示区域时不显示椭圆
- acumatica - 智能面板中的选择器给出错误'
在系统中找不到。 - c# - 如何使主栏中的页面对除管理员以外的所有人隐藏?
- c# - 从 C# 控制台应用程序打开网页
- php - 如何避免 php 解析整个 php 文件并包含并使其仅解析将使用的内容?