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

TypeScript按公共键比较对象数组触发TS2367错误如何解决?

TS2367错误解决方案

错误根因

当前泛型仅约束了比较键K是两个数组元素类型T、U的共有键,没有限制二者在K上的取值类型相同,TypeScript认为两个无重叠类型的恒等判断永远返回false,因此抛出该错误。

修正后代码

const sourceArray = [{requestId: "1", name: "henry"},{requestId: "2", name: "bob"}] 
const arrayListToCompareWith = [{requestId: "1", age: 30}, {requestId: "9", age: 40}]
const commonItems = getCommonItemsByKey(sourceArray, arrayListToCompareWith, "requestId")

function getCommonItemsByKey<
  // 约束比较键为合法的对象键类型
  K extends PropertyKey,
  // 约束源数组元素类型必须包含比较键K
  T extends Record<K, unknown>,
  // 约束对比数组元素类型的K键取值,和源数组K键取值类型一致
  U extends Record<K, T[K]>
>(
  sourceArray: T[],
  compareArray: U[],
  compareKey: K
): T[] {
  // 优化点:先提取所有对比键的值存入Set,仅单次遍历,后续匹配时间复杂度为O(1)
  const compareValueSet = new Set(compareArray.map(item => item[compareKey]))
  return sourceArray.filter(item => compareValueSet.has(item[compareKey]))
}

运行效果

修正后不会再触发TS2367错误,最终commonItems会返回符合预期的公共元素:

[{requestId: "1", name: "henry"}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:45:03