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

TypeScript循环中解构联合类型参数的类型关联问题

解决TypeScript中联合类型属性配对的索引安全问题

问题分析

你的代码中,ArrayItem是三个对象的联合类型,但TypeScript无法追踪type与units的关联关系——解构后type变为'mean'|'median',units变为'a'|'b'|'d',导致group[units]的索引操作无法通过类型检查,因为TS无法确认当前group的键是否包含units的值。

惯用解决方案:泛型约束关联属性

利用TypeScript的泛型分布式特性,让函数参数的type和units建立强关联,确保索引安全:

const someObject = {
  mean: { a: 100, b: 200 },
  median: { c: 300, d: 400 },
} as const;

const someArray = [
  { type: 'mean', units: 'a' },
  { type: 'mean', units: 'b' },
  { type: 'median', units: 'd' },
] as const;

// 泛型函数,约束type与units的关联
function accessItem<K extends keyof typeof someObject>({ type, units }: { 
  type: K; 
  units: keyof (typeof someObject)[K] 
}) {
  const group = someObject[type];
  const value = group[units]; // TS可正确识别units是group的合法键
  return value;
}

const resultArray = someArray.map(accessItem); // 类型推导为 readonly [100, 200, 400]

原理说明

  • 泛型参数K被约束为someObject的键类型('mean'|'median'),当处理联合类型的每个成员时,TS会为每个K单独推导类型;
  • units被约束为someObject[K]的键类型,确保当type为'mean'时,units只能是'a'|'b',当type为'median'时,units只能是'c'|'d';
  • 这种方式利用了TypeScript的泛型分布式特性,自动为联合类型的每个成员建立属性关联,避免了类型交叉丢失的问题。

内容的提问来源于stack exchange,提问作者Michał Sadowski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:18:23