React组件Props类型推断:移除any并推导额外Props
React动态组件Props的类型安全实现
要移除[key: string]: any并实现额外Props的自动类型推断,核心是利用TypeScript泛型结合React内置的ComponentProps工具类型,让TypeScript根据传入的component类型自动推导对应的Props约束。
修改后的Button组件实现
import { PropsWithChildren, ElementType, ComponentProps } from 'react'; // 定义泛型Props类型:固定component属性 + 对应元素的Props(排除children,由PropsWithChildren统一处理) type ButtonProps<C extends ElementType> = PropsWithChildren<{ component: C; } & Omit<ComponentProps<C>, 'children'>>; // 泛型组件,默认渲染button标签 export const Button = <C extends ElementType = 'button'>( props: ButtonProps<C> ) => { const { component: Component = 'button', children, ...restProps } = props; return <Component {...restProps}>{children}</Component>; };
关键逻辑说明
- 泛型约束:用
C extends ElementType限制component的类型,可以是原生HTML标签(如'button'、'a')或自定义组件。 - 自动推导Props:通过
ComponentProps<C>获取传入组件的完整Props类型,再用Omit排除children(避免与PropsWithChildren的children属性冲突)。 - 默认值处理:给泛型
C设置默认值'button',用户不传入component时,默认使用button标签并自动获得button的Props类型约束。 - 类型安全验证:当传入的Props与
component类型不匹配时,TypeScript会直接报错。比如给component='button'传入href属性,会提示button标签不存在该属性。
用法示例
// 合法:a标签支持href属性 <Button component='a' href='/home' target='_blank'> 跳转到首页 </Button> // 合法:button标签支持disabled属性 <Button component='button' disabled> 不可点击按钮 </Button> // 报错:button标签没有href属性 <Button component='button' href='x'> Push Me </Button>
内容的提问来源于stack exchange,提问作者CzechCoder
相关产品推荐
相关产品推荐

