You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确使用带两种Props的HOC?TypeScript类型不兼容问题排查

解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:57:49