【发布时间】:2017-09-26 14:33:36
【问题描述】:
我正在用 TypeScript 写一个React higher-order component (HOC)。 HOC 应该比被包装的组件多接受一个 prop,所以我写了这个:
type HocProps {
// Contains the prop my HOC needs
thingy: number
}
type Component<P> = React.ComponentClass<P> | React.StatelessComponent<P>
interface ComponentDecorator<TChildProps> {
(component: Component<TChildProps>): Component<HocProps & TChildProps>;
}
const hoc = function<TChildProps>(): (component: Component<TChildProps>) => Component<HocProps & TChildProps) {
return (Child: Component<TChildProps>) => {
class MyHOC extends React.Component<HocProps & TChildProps, void> {
// Implementation skipped for brevity
}
return MyHOC;
}
}
export default hoc;
换句话说,hoc 是一个产生实际 HOC 的函数。这个 HOC 是(我相信)一个接受 Component 的函数。由于我事先不知道被包装的组件会是什么,所以我使用泛型类型TChildProps 来定义被包装组件的道具的形状。该函数还返回一个Component。返回的组件接受包装组件的道具(同样,使用通用 TChildProps 键入)和它自己需要的一些道具(类型 HocProps)。使用返回的组件时,应提供所有的道具(HocProps 和包装的Component 的道具)。
现在,当我尝试使用我的 HOC 时,我会执行以下操作:
// outside parent component
const WrappedChildComponent = hoc()(ChildComponent);
// inside parent component
render() {
return <WrappedChild
thingy={ 42 }
// Prop `foo` required by ChildComponent
foo={ 'bar' } />
}
但我收到 TypeScript 错误:
TS2339: Property 'foo' does not exist on type 'IntrinsicAttributes & HocProps & {} & { children? ReactNode; }'
在我看来,TypeScript 并没有将 TChildProps 替换为 ChildComponent 所需的道具形状。我怎样才能让 TypeScript 做到这一点?
【问题讨论】:
标签: reactjs typescript higher-order-components