Javascript React HOC和TypeScript 3.2
随着TypeScript在v3.2中改进其JSX类型检查,我们现在有一个正确键入HOC的问题 有人可以为TypeScript 3.2修复以下HOC中的类型吗Javascript React HOC和TypeScript 3.2,javascript,reactjs,typescript,higher-order-components,Javascript,Reactjs,Typescript,Higher Order Components,随着TypeScript在v3.2中改进其JSX类型检查,我们现在有一个正确键入HOC的问题 有人可以为TypeScript 3.2修复以下HOC中的类型吗 import { ComponentType } from 'react'; type Props = { custom: string }; type Omit<T, K extends string> = Pick<T, Exclude<keyof T, K>>; function hoc<
import { ComponentType } from 'react';
type Props = { custom: string };
type Omit<T, K extends string> = Pick<T, Exclude<keyof T, K>>;
function hoc<P extends Props>(Component: ComponentType<P>) {
return (props: Omit<P, keyof Props>) => {
return <Component {...props} custom="text" />;
}
}
基本上,这个想法是将需要“自定义”属性的组件转换为不再需要它的组件,因为它将由HOC自动注入
编辑:
可能是同一个问题:我肯定这不是您所希望的答案,但是您可以通过将内部函数中的
道具的类型更改为任意,并将省略类型放在外部函数的返回类型注释中来实现,如下所示:
function hoc<P extends Props>(Component: ComponentType<P>): ComponentType<Omit<P, keyof Props>> {
return (props: any) => {
return <Component {...props} custom="text" />;
}
}
函数hoc(组件:组件类型
):组件类型{
返回(道具:任意)=>{
返回;
}
}
我对新的TS 3.2.1也有同样的问题,我认为这是一个bug。我推迟了道具
到任何
的铸造,直到传播,所以我使用了{(…this.props as any)}
,所以你仍然可以在渲染函数的其他地方使用键入的道具。到目前为止,这是最不具侵入性的解决方案。谢谢…这个答案的问题是,您返回的组件不会对其道具进行打字检查
function hoc<P extends Props>(Component: ComponentType<P>): ComponentType<Omit<P, keyof Props>> {
return (props: any) => {
return <Component {...props} custom="text" />;
}
}