You need to enable JavaScript to run this app. TypeScript遍历联合类型对象无法访问非共有属性如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript遍历联合类型对象无法访问非共有属性如何解决?

解决方案

方案1:将Props定义为可辨识联合(最推荐)

核心问题是原始Props定义中attributionType和attributions的类型没有绑定关联,即使你判断了attributionType的取值,TypeScript也无法推导对应attributions的具体类型。
将Props改为可辨识联合类型即可让TypeScript自动完成类型收窄:

interface Family {
  cat: string;
  age: string;
  family: string;
  lastYearFamily: string;
}

interface Model {
  cat: string;
  age: string;
  model: string;
  lastYearModel: string;
}

// 改为可辨识联合,将两个属性的类型关联
type Props = 
  | {
      attributionType: 'family';
      attributions?: Family[];
    }
  | {
      attributionType: 'model';
      attributions?: Model[];
    }

const RowComponent = ({
  attributionType,
  attributions
}: Props) => {
  return (
    <>
      {attributions?.map((attribution) => (
        <tr key={`${attribution.cat}-${attribution.age}`}>
          {attributionType === 'family' && (
            <>
              <th>{attribution.family}</th>
              <th>Family</th>
            </>
          )}
          {attributionType === 'model' && (
            <>
              <th>{attribution.model}</th>
              <th>Model</th>
            </>
          )}
        </tr>
      ))}
    </>
  )
}

修改后无需额外判断,TypeScript会在你判断attributionType取值后自动收窄attribution的类型,直接访问对应独有属性不会报错。

方案2:自定义类型守卫(适合无法修改Props定义的场景)

如果不能改动现有Props的定义,可以通过自定义类型守卫手动收窄类型:

// 新增类型守卫函数
const isFamily = (attr: Family | Model): attr is Family => {
  return 'family' in attr;
}
const isModel = (attr: Family | Model): attr is Model => {
  return 'model' in attr;
}

// 组件使用时新增守卫判断
const RowComponent = ({
  attributionType,
  attributions
}: Props) => {
  return (
    <>
      {attributions?.map((attribution) => (
        <tr key={`${attribution.cat}-${attribution.age}`}>
          {attributionType === 'family' && isFamily(attribution) && (
            <>
              <th>{attribution.family}</th>
              <th>Family</th>
            </>
          )}
          {attributionType === 'model' && isModel(attribution) && (
            <>
              <th>{attribution.model}</th>
              <th>Model</th>
            </>
          )}
        </tr>
      ))}
    </>
  )
}

方案3:类型断言(临时快速解决)

如果确定业务逻辑不会出现类型错配,可以直接用类型断言跳过TS检查,不推荐大规模使用:

attributionType === 'family' && (
  <>
    <th>{(attribution as Family).family}</th>
    <th>Family</th>
  </>
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 03:45:04