如何正确使用带两种Props的HOC?TypeScript类型不兼容问题排查
你遇到的这个报错核心是组件的props类型和HOC的参数要求不匹配,咱们一步步拆解来看:
首先看你的withBaseProps高阶组件定义,它要求传入的WrappedComponent必须是ComponentType<ComponentProps>——也就是这个组件得接受ComponentProps类型的参数。但你传给它的CreateComponentHere却是一个接受BaseProps的组件,这俩类型完全不兼容,TypeScript自然会报错。
问题出在哪?
你的HOC逻辑是:接收一个能处理ComponentProps的组件,然后返回一个能处理BaseProps的组件——返回的组件会把BaseProps里的valueForComponentProp转换成ComponentProps的componentprop,再传递给被包裹的组件。但你现在写的CreateComponentHere却要求接收BaseProps,和HOC的预期完全相反。
怎么修复?
最直接的方案是修正CreateComponentHere的props类型,让它符合HOC的要求(接收ComponentProps):
// 把CreateComponentHere的props类型改成ComponentProps function CreateComponentHere(props: ComponentProps): JSX.Element { // 这里直接把props传给底层组件即可 return <ComponentWithComponentProps {...props} />; } // 现在这行就不会报错了 export const NewComponent = withBaseProps<BaseProps>(CreateComponentHere);
为什么这样改?
当你调用NewComponent时,传入的是BaseProps,HOC会自动把它转换成ComponentProps传递给CreateComponentHere,而CreateComponentHere现在正好能接收ComponentProps,类型链条就完全通顺了。
如果你的业务场景确实需要CreateComponentHere接收BaseProps,那你得调整HOC的类型定义,让它接受能处理BaseProps的组件,但这时候要确保HOC传递给组件的props和组件期望的一致——不过从你的代码逻辑来看,第一种方案才是符合你封装意图的正确做法。
内容的提问来源于stack exchange,提问作者HoloLady

