我想创建一个返回高阶组件的高阶函数。
在下面的示例中,我创建了一个validateSearchParams
函数,该函数创建了一个可用于包装组件的函数。但是,Typescript (3.7.2) 无法正确推断类型。
export function validateSearchParams<Props extends { location: Location }>(
test: (searchParams: URLSearchParams) => boolean,
redirectTo: string,
): (Cmp: React.ComponentType<Props>) => React.ComponentType<Props> {
return (Cmp) => (props) => {
const searchParams = new URLSearchParams(props.location.search);
if (!test(searchParams)) {
return <Redirect to={redirectTo} />;
}
return <Cmp {...props} />;
};
}
export const Test: React.FC<{ something: boolean; location: Location }> = () => null;
// This is OK
validateSearchParams<{ something: boolean; location: Location }>(
(searchParams) => !!searchParams.get('foo'),
'hxxp://somewhere',
)(Test);
// ...but without an explicit type it does not compile
validateSearchParams((searchParams) => !!searchParams.get('foo'), 'http://test.example')(Test);
^^^^
在最后一行中,我收到以下错误:
Argument of type 'FC<{ something: boolean; location: Location; }>' is not assignable to
parameter of type 'ComponentType<{ location: Location; }>'.
Type 'FC<{ something: boolean; location: Location; }>' is not assignable to type
'FunctionComponent<{ location: Location; }>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'PropsWithChildren<{ location: Location; }>' is not assignable to type
'PropsWithChildren<{ something: boolean; location: Location; }>'.
Property 'something' is missing in type 'PropsWithChildren<{ location: Location; }>' but
required in type '{ something: boolean; location: Location; }'.ts(2345)
Cmp
通过将参数列表合并,我还可以创建一个更简单的 HOC 版本:
export function validateSearchParams2<Props extends { location: Location; match: match<any> }>(
Cmp: React.ComponentType<Props>,
test: (searchParams: URLSearchParams) => boolean,
redirectTo: string,
): React.ComponentType<Props> {
return (props) => {
const searchParams = new URLSearchParams(props.location.search);
if (!test(searchParams)) {
return <Redirect to={redirectTo} />;
}
return <Cmp {...props} />;
};
}
export const Test: React.FC<{ something: boolean; location: Location }> = () => null;
validateSearchParams2(Test, (searchParams) => !!searchParams.get('foo'), 'hxxp://somewhere');
...但是有没有办法在validateSearchParams
没有明确类型的情况下制作作品的第一个版本?