0

我想创建一个返回高阶组件的高阶函数

在下面的示例中,我创建了一个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没有明确类型的情况下制作作品的第一个版本?

4

1 回答 1

1

现在泛型类型Props设置在 function 上validateSearchParams。您想将泛型移动到返回的函数。基本上validateSearchParams不是泛型函数,它返回一个泛型 HOC。

export function validateSearchParams(
  test: (searchParams: URLSearchParams) => boolean,
  redirectTo: string,
): <Props extends { location: Location }>(Cmp: React.ComponentType<Props>) => React.ComponentType<Props> {
...

现在您不需要设置显式类型,因为它可以从您调用它的组件中推断出来。

打字稿游乐场链接

于 2021-01-31T20:58:59.230 回答