如何在 react-typescript 中设置 HOC 中的props类型?

IT技术 reactjs typescript higher-order-components
2022-08-03 01:59:26

我有一个简单的 withAuth HOC。我正在尝试定义props的类型。

const withAuth = (Component: typeof React.Component) => (role: string) => {
  return (props) => {
    const { data, loading } = useGetUser();
    if (loading) {
      return <p>Loading...</p>;
    }

    if (!data) {
      return <Redirect ssr to="/api/v1/login" />;
    } else {
      if (role && !isAuthorized(data, role)) {
        return <Redirect ssr to="/api/v1/login" />;
      }

      return <Component user={data} loading={loading} {...props} />;
    }
  };
};

我试过这个:

React.Component<T>

然后传递Tprops:T我收到2个警告。

  Component: typeof React.Component<T> // Parameter '(Missing)' implicitly has an 'any' type.

 props:T // Cannot find name 'T'
1个回答

在这里你有:


import React, { FC } from 'react'

type Props = {
  name: string
}

const A: FC<Props> = () => <div></div>


const withAuth = <P extends object>(Component: React.ComponentType<P>) => (role: string) => {
  return (props: P) => {
    return <Component {...props} />;
  }
};

const result1 = withAuth(A)('hello')({ label: 'hello' }) // error
const result2 = withAuth(A)('hello')({ name: 'hello' }) // ok