How can I set the props type in HOC in react-typescript?

自古美人都是妖i 提交于 2021-01-28 20:04:17

问题


I have a simple withAuth HOC. I am trying to define the type for 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} />;
    }
  };
};

I tried this:

React.Component<T>

Then passing the T to props:T i am getting 2 warnings.

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

 props:T // Cannot find name 'T'

回答1:


Here you have:


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



来源:https://stackoverflow.com/questions/65414467/how-can-i-set-the-props-type-in-hoc-in-react-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!