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

React组件Props条件类型定义求助:禁止无title时传description

解决React组件Props类型限制:禁止单独传入description

要实现仅当传入title时才允许传入description的约束,你需要用互斥的联合类型明确合法的Props组合,而非简单的可选字段叠加。

问题分析

你之前的代码:

type Props = { title?: string; description?: string } | { title?: never; description?: never };

之所以无效,是因为第一个类型分支{ title?: string; description?: string }已经允许单独传入description(此时title可省略),第二个分支对错误场景没有限制作用。

正确实现

通过拆分合法的Props组合,用联合类型限定仅允许以下三种情况:

  1. 什么都不传
  2. 仅传入title
  3. 同时传入title和description

对应的类型定义:

type Props = 
  | { title?: never; description?: never } // 无参数
  | { title: string; description?: string }; // 有title,description可选

更简洁的等价写法:

type Props = {} | { title: string; description?: string };

验证场景

  • ✅ 合法使用:
    <Component />
    <Component title="标题" />
    <Component title="标题" description="描述" />
    
  • ❌ 非法使用(TypeScript会报错):
    <Component description="描述" />
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:27:03