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

React + TypeScript 中Button组件的依赖Props类型安全实现问题

React Button组件的TypeScript类型安全实现问题

我实现了一个React Button组件:

function Button({ text, Icon, iconProps, ...buttonProps }: ButtonProps)

该组件的props必须满足以下结构要求:

  • 仅包含text
  • 仅包含Icon
  • 包含Icon及对应的iconProps(仅当存在Icon时才能传入iconProps)
  • 同时包含text和Icon
  • 同时包含text、Icon和iconProps
  • props不能为空,至少要有text或Icon

如果把所有props设为可选会丢失我想要的类型安全性。我尝试为每种场景创建接口并进行联合,但该方案既不生效也不够简洁优雅:

interface ButtonOnlyText extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  text: string;
}

interface ButtonOnlyIcon extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  Icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
}

interface ButtonIconWithProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  Icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
  iconProps: React.SVGProps<SVGSVGElement>;
}

interface ButtonTextAndIcon extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  text: string;
  Icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
}

interface ButtonComplete extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  text: string;
  Icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
  iconProps: React.SVGProps<SVGSVGElement>;
}

type ButtonProps = ButtonOnlyText | ButtonOnlyIcon | ButtonIconWithProps | ButtonTextAndIcon | ButtonComplete

declare function Button({ text, Icon, iconProps, ...buttonProps }: ButtonProps): React.FC;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:47:40