【发布时间】:2021-07-20 13:55:12
【问题描述】:
我正在尝试实现一个简单的 HOC,以使用自定义工具提示来增强组件。虽然代码工作正常,但我无法弄清楚如何正确声明类型。 我的 HOC 的简化版本如下所示:
const withTooltip = <P extends {}>(
BaseComponent: React.ComponentType<P>
): React.FC<P & { title?: string }> => ({ title, ...rest }) => {
return (
<>
<BaseComponent {...rest} />
<Tooltip title={title}/>
</>
);
};
但我收到了 Typescript 错误:
Type 'Omit<PropsWithChildren<P & { title?: string | undefined; }>, "title">' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
Type 'Omit<PropsWithChildren<P & { title?: string | undefined; }>, "title">' is not assignable to type 'P'.
'Omit<PropsWithChildren<P & { title?: string | undefined; }>, "title">' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint '{}'.
如何正确声明此类 HOC 的类型?
【问题讨论】:
标签: reactjs typescript