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

React+TS使用联合类型定义Props时无法访问属性如何解决

问题原因与解决方案

你的类型定义本身是符合需求的,报错是由两处代码写法问题导致的:

  • 你在参数解构时将可辨识属性type和其余属性拆分为两个独立变量,TypeScript 无法自动关联两者的类型关系,即便你判断了type为dropdown,也无法推断剩余的props包含options属性
  • case 'text' || 'number'的写法不符合语法逻辑:该表达式会先运算得到固定值'text',只有type为text时会进入该分支,type为number时无法匹配,也不符合你的预期

修复方案

不要拆分参数直接使用完整的props对象做类型收窄即可,TypeScript 可以正常基于type属性推断同对象下的其他属性类型:

type DetailsItemEditInput = {
  type: 'text' | 'number';
};

type DetailsItemEditDropdown = {
  type: 'dropdown';
  options: [];
};

type DetailsItemEdit = DetailsItemEditDropdown | DetailsItemEditInput;

export const DetailsItemEdit: FC<DetailsItemEdit> = (props) => {
  switch (props.type) {
    // 多case叠加匹配text和number类型
    case 'text':
    case 'number':
      return <Input type={props.type} />;
    case 'dropdown':
      // 此时TS可正常推断props为DetailsItemEditDropdown类型,存在options属性
      return <Select options={props.options} />;
    default:
      return <div style={{ color: 'red' }}>Wrong type</div>;
  }
};

如果你一定要保留解构写法,可以在访问options前加类型判断,比如if ('options' in props),但直接使用完整props对象做收窄是最简单高效的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:36:03