如何扩展React组件中被推断的未导出TypeScript接口?
如何扩展未导出的React组件Props接口
当你使用的第三方库只导出了组件(比如示例中的Button)但未导出对应的Props接口时,可以通过TypeScript结合React内置的工具类型来获取并扩展该组件的Props类型,具体方法如下:
核心方法:使用React内置工具类型获取组件Props
React提供了两个专门用于提取组件Props类型的工具类型:
React.ComponentProps<typeof Component>:提取组件的完整Props类型(包含ref)React.ComponentPropsWithoutRef<typeof Component>:提取不含ref的Props类型(不需要处理ref时推荐使用)
方案1:交叉类型直接扩展
直接通过交叉类型将原有Props和自定义属性合并:
import { Button } from '你的库路径'; // 扩展Button的Props,添加text属性 type GenericButtonProps = React.ComponentPropsWithoutRef<typeof Button> & { text: string; };
方案2:先提取再接口继承
如果更习惯用接口继承的方式,可以先提取原有Props类型,再进行扩展:
import { Button } from '你的库路径'; // 提取Button未导出的Props类型 type ButtonInternalProps = React.ComponentPropsWithoutRef<typeof Button>; // 扩展接口 interface GenericButtonProps extends ButtonInternalProps { text: string; }
为什么之前的Button['props']写法无效?
函数组件本身并没有props这个属性,Button['props']是类组件的写法(类组件实例存在props属性),而函数组件的Props类型必须通过React提供的工具类型来提取,这就是你之前尝试失败的原因。
验证:使用扩展后的类型编写包装组件
function GenericButton({ text, ...restProps }: GenericButtonProps) { return <Button {...restProps}>{text}</Button>; }
内容的提问来源于stack exchange,提问作者Alejandro B.
相关产品推荐
相关产品推荐

