TypeScript中如何处理接口内扩展运算符,允许React组件接收额外Props
React组件Props扩展解决方案
问题场景
现有如下React TypeScript组件,使用扩展运算符提取自定义属性后传递剩余props,但传递onClick等原生按钮属性时,会触发类型错误:props无法分配给类型“IntrinsicAttributes & ButtonProps”。
原组件代码:
interface ButtonProps { colourMode: string; regular: boolean; buttonText: string; disabled?: boolean; iconSize?: string; iconLeft?: React.ReactNode; iconRight?: React.ReactNode; } const LowProButton = (props: ButtonProps) => { const { colourMode, buttonText, disabled, iconSize, iconLeft, iconRight, ...other } = props; // 后续使用other传递到底层按钮元素 };
报错的使用示例:
<LowProButton iconSize="14" regular={false} iconLeft={<RestartAltIcon />} colourMode="secondary" buttonText="Detailed" onClick={props.performClick} // 此处触发类型错误 />
解决方案
要同时保留自定义强类型属性,又支持传递任意合法的按钮原生props,只需让ButtonProps继承React提供的原生按钮属性类型:
修改接口定义
让ButtonProps继承React.ButtonHTMLAttributes<HTMLButtonElement>,该类型包含了所有原生HTML按钮的标准属性(如onClick、disabled、className等),同时保留自定义的强类型字段:
import React from 'react'; interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { colourMode: string; regular: boolean; buttonText: string; iconSize?: string; iconLeft?: React.ReactNode; iconRight?: React.ReactNode; }
注意:如果你的组件底层不是
<button>元素(比如用<div>模拟按钮),则替换为对应元素的属性类型,比如React.HTMLAttributes<HTMLDivElement>。
组件使用说明
修改后,组件可以正常接收自定义属性和所有原生按钮属性,同时TypeScript会自动校验属性的合法性:
<LowProButton iconSize="14" regular={false} iconLeft={<RestartAltIcon />} colourMode="secondary" buttonText="Detailed" onClick={props.performClick} // 不再报错 disabled={true} // 原生属性也会被正确类型校验 />
原理说明
通过继承原生元素的属性类型,我们无需手动声明所有可能的原生props,同时TypeScript会确保传递的props既符合自定义要求,又符合原生元素的规范,实现强类型和扩展性的平衡。
内容的提问来源于stack exchange,提问作者Squiggs.
相关产品推荐
相关产品推荐

