Def*_*mat 26 javascript typescript reactjs 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<P extends Props>(Component: ComponentType<P>) {
return (props: Omit<P, keyof Props>) => {
return <Component {...props} custom="text" />;
}
}
Run Code Online (Sandbox Code Playgroud)
TypeScript错误:
Type '{ custom: string; }' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'.
Property 'custom' does not exist on type 'IntrinsicAttributes & P & { children?: ReactNode; }'
Run Code Online (Sandbox Code Playgroud)
基本上,我们的想法是将需要"自定义"属性的组件转换为组件,而不再需要它,因为它将由HOC自动注入.
编辑:可能同样的问题:https://github.com/Microsoft/TypeScript/issues/28748
props我确信这不是您所希望的答案,但是您可以通过将内部函数中的类型更改为any,并将该Omit类型放入外部函数的返回类型注释中来使其工作,如下所示:
function hoc<P extends Props>(Component: ComponentType<P>): ComponentType<Omit<P, keyof Props>> {
return (props: any) => {
return <Component {...props} custom="text" />;
}
}
Run Code Online (Sandbox Code Playgroud)