TypeScript中如何定义仅需指定新增Props类型的通用HOC
问题根因
报错源于TypeScript的核心泛型规则:不支持部分指定泛型参数。当一个泛型函数声明了多个类型参数时,调用时要么全部手动传入类型参数,要么全部依赖入参自动推导,原生不支持「手动传入第一个新增Props类型,第二个组件Props类型从入参自动推导」的行为。
实现方案
采用双层柯里化泛型结构改造HOC即可实现你要的调用体验,这也是styled-components实现同款类型推导逻辑的核心思路:
将两个泛型参数拆分到两层函数调用上:第一层接收你手动指定的新增Props类型,第二层接收被包裹组件并自动推导组件自身的Props类型,绕开TS不支持部分泛型参数指定的限制。
修正后的完整实现:
import type { FC } from 'react'; export const withMoreProps = <NewProps extends object>() => <Props extends object>(WrappedComponent: FC<Props>): FC<Props & NewProps> => { const displayName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; const ComponentWithMoreProps = (props: Props & NewProps) => <WrappedComponent {...props} />; ComponentWithMoreProps.displayName = `withMoreProps(${displayName})`; return ComponentWithMoreProps; };
使用时仅需手动传入新增的Props类型,被包裹组件的原有Props会被自动推导,无需手动声明:
const Button = (props: { color: string }) => <button style={{ color: props.color }}>BTN</button>; // 仅指定新增属性类型,原有Props自动推导 export const Button2 = withMoreProps<{ newProperty: string }>()(Button); // 类型校验正常:使用时需同时传入原有color属性和新增newProperty属性 const App = () => <Button2 color="red" newProperty="test" />;
该方案兼容TypeScript 3.4及以上所有版本,类型推导完全精准,你可以直接在这个结构上叠加业务HOC的其他逻辑,不会影响类型推导效果。
内容的提问来源于stack exchange,提问作者Konrad Klimczak
相关产品推荐
相关产品推荐

