仅当使用“--downlevelIteration”标志或使用“es2015”或更高版本的“--target”时,才能迭代类型“Set<unknown>”

Joh*_*han 34 typescript reactjs

我试图获取数组中的所有 id,然后使用 React TypeScript 删除重复项。

这是我的代码:

const uniqueMuscle = workoutexercices.map((exercice: any) => {
    let exercicesId = exercice.id;
    exercicesId = [...new Set(exercicesId)];
    return exercicesId;
  });
Run Code Online (Sandbox Code Playgroud)

VSCode[...new Set(exercicesId)];用红色下划线告诉我: Type 'Set<unknown>' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher

所以我去了我的ts.config并更改了值,但仍然是相同的错误。

这是我的ts.config

{
  "compilerOptions": {
    "target": "es2015",
I   "downlevelIteration": true
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}
Run Code Online (Sandbox Code Playgroud)

知道为什么我一直出现此错误吗?

小智 26

问题是您想要使用仅在 ES2015 JavaScript 版本中可用的功能。

解决方案是更新 tsconfig.json 文件,更改"target"为至少"es2015"(也称为"es6")。

{
  "compilerOptions": {
    "target": "es2015",
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

来源:TSConfig 目标选项

  • 如果您使用 Next.js,并且在更改目标后仍然遇到此错误,请通过执行“rm -rf .next”清除下一个缓存,它应该可以工作。否则您可能会看到错误的 tsconfig.json 文件。 (3认同)

小智 11

尝试 exercicesId = Array.from(new Set(exercicesId));


小智 9

有同样的错误,将 tsconfig.json 从 CommonJS 设置为带有 target、module、moduleResolution 的 Es 模块对我有帮助。

我的 tsconfig.json:

    "compilerOptions": {
        "target": "ES2020",
        "module": "ESNext",
        "moduleResolution": "NodeNext",
        "jsx": "react-jsx",
        "baseUrl": "./",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
} 
Run Code Online (Sandbox Code Playgroud)