React+Typescript自定义PrivateRoute出现Property does not exist报错如何解决
问题根因
你定义的IPrivateRouteProps接口只声明了component一个属性,但你使用PrivateRoute的时候传入了path、exact等额外属性,TypeScript在编译阶段校验组件入参时,发现这些属性没有在组件的入参类型中定义,就抛出了类型不匹配的错误。
你虽然用了展开运算符...rest接收剩余属性,但这是运行时的逻辑,不会影响TypeScript编译阶段的类型校验规则。
解决方案
让IPrivateRouteProps继承react-router-dom内置的RouteProps类型,RouteProps已经包含了path、exact、strict等所有Route组件支持的属性,修改后的代码如下:
import { Route, RouteProps, Redirect } from 'react-router-dom'; // 继承RouteProps获取所有Route支持的属性 interface IPrivateRouteProps extends RouteProps { // 重写component为必填属性(原RouteProps中component是可选的) component: React.ElementType; } export function PrivateRoute({ component: Component, ...rest }: IPrivateRouteProps): JSX.Element { return ( <Route {...rest} render={(props) => isAuthenticated() ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: "/login", state: { from: props.location } }} /> ) } /> ); }
补充说明
你当前使用的是react-router-dom v5的写法,如果你后续升级到v6版本,私有路由的实现逻辑会有较大调整,不再支持Switch、Redirect、render属性等API,需要对应调整实现。
内容的提问来源于stack exchange,提问作者Eduardo Augusto
相关产品推荐
相关产品推荐

