首页 > 解决方案 > 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

标签: javascripttypescript

解决方案


数组应该用数字索引,而不是字符串。但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)
  }
};

推荐阅读