React + TypeScript 中Button组件的依赖Props类型安全实现问题
我实现了一个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
相关产品推荐
相关产品推荐

