You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中Set类型union函数报错问题咨询

解决TypeScript Set合并函数的两个报错问题

修正后的代码

function union<T>(setA: Set<T>, setB: Set<T>) {
  const _union = new Set(setA);
  for (const elem of setB) {
    _union.add(elem);
  }
  return _union;
}

错误原因及解决步骤

1. 移除错误的Set类型导入

你代码里的import type {Set} from 'typescript'是核心问题之一:

  • 该导入的是TypeScript内部的类型定义,并非JavaScript全局环境中Set构造函数对应的类型。
  • 全局的Set类型已经通过lib: ["esnext"]配置自动引入,完全不需要手动导入。
  • 移除该行后,new Set(setA)的重载匹配错误(TS2769)会直接解决。

2. 开启downlevelIteration配置

针对for (const elem of setB)的TS2495错误,需要修改tsconfig.json:
在compilerOptions中添加"downlevelIteration": true,修正后的配置如下:

{
    "compilerOptions": {
        "sourceMap": true,
        "outDir": "dist",
        "module": "commonjs",
        "target": "es5",
        "lib": ["esnext"],
        "esModuleInterop": true,
        "downlevelIteration": true
    },
    "exclude": [
        "node_modules"
    ],
    "include": [
        "src/**/*"
    ]
}
  • 当target设为es5时,TypeScript默认不会为ES6+的集合类型(如Set)提供迭代器的类型支持,也不会编译for...of循环到兼容ES5的代码。
  • 开启downlevelIteration后,TypeScript会处理迭代器的兼容性,同时类型检查会认可Set的可迭代性,彻底解决该报错。

内容的提问来源于stack exchange,提问作者Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 11:35:22