用另一个React组件包装组件的Typescript函数



我有一个函数,它用<IntlContextProvider>组件封装React组件。我想定义GenericFunctionType,但我不知道应该是什么。

const wrapIntl: GenericFunctionType = (ComponentToWrap)  => {
class Wrapper extends React.PureComponent {
render() {
return (
<IntlContextProvider>
<ComponentToWrap {...this.props}/>
</IntlContextProvider>
);
}
}
return Wrapper;
}

此函数wrapIntl的使用方式如下:


export const TranslateText = wrapIntl(({text}: {text: string}) =>
<>
{React.useContext(IntlContext).translate(text)}
</>
)

我现在有这个:

interface GenericFunctionType {
<T>(ComponentToWrap: React.ReactNode): T
}

但它有这样的错误:

TS2322:Type'(ComponentToWrap:ReactNode(=>typeof Wrapper"不可分配给类型"WrapIntlFunctionType"。类型"typeof Wrapper"不可分配给类型"T"。"T"可以用任意类型实例化,该类型可能与"typeof Wrapper"无关。

TS2604:JSX元素类型"ComponentToWrap"没有任何构造或调用签名。

您有正确的想法使其通用。T将是道具的类型,您可以让它接受并返回React.ComponentType<T>:

interface GenericFunctionType {
<T,>(ComponentToWrap: React.ComponentType<T>): React.ComponentType<T>
}

游乐场链接

尽管它的显式类型并不是真正必要的,但您可以在实现上指定类型(无论如何都需要这样做,因为您需要在Wrapper类定义中使用T(:


const wrapIntl = <T,>(ComponentToWrap: React.ComponentType<T>): React.ComponentType<T> => {
class Wrapper extends React.PureComponent<T> {
render() {
/// ....
}
}
return Wrapper;
}

游乐场链接

最新更新