HOC中传递的组件类型是什么



我正在使用AWS Amplify将protectedRoute HOC从Javascript转换为TypeScript。

该HOC将用于保护任何需要身份验证的路由。如果用户没有登录,它会将他们重定向到特定的路由。

import React, { useEffect } from "react";
import { Auth } from "aws-amplify";

interface Props {
history: string[];
}
const protectedRoute = (Comp: React.FunctionComponent, route = "/profile") => (
props: Props
) => {
async function checkAuthState() {
try {
await Auth.currentAuthenticatedUser();
} catch (error) {
props.history.push(route);
}
}
useEffect(() => {
checkAuthState();
}, []);
return <Comp {...props} />;
};
export default protectedRoute;

将HOC用于受保护路线的示例

const Protected = () => {
return <Container>Protected</Container>;
};
export default protectedRoute(Protected);

我从<Comp {...props} />:得到的错误

Type '{ history: string[]; }' has no properties in common with type 'IntrinsicAttributes & { children?: ReactNode; }'

我不知道Comp使用什么类型,但我正在传递一个功能组件,const Protected返回一个JSX.Element

我尝试将Comp设置为React.ReactNode,但得到了相同的结果。

我也知道这个问题的答案提到我应该只使用any,但我想知道这里是否有合适的类型。

使用React.FunctionComponent<Props>显式告诉类型使用Props接口。

请注意,children道具隐含地包含在React.FunctionComponent中,但这将在@types/react的未来版本中发生变化。你可以在这里阅读更多信息。

最新更新