TSX路由鉴权场景下TypeScript提示Route组件Component隐式any类型报错如何解决
私有路由组件TypeScript类型报错解决方案
报错原因
入参component未显式定义类型,被TypeScript隐式推断为any,触发ts(7031)类型校验规则。同时原有代码存在箭头函数无返回值的语法问题。
完整修复后代码
import React from 'react'; import { Redirect, Route, RouteProps } from 'react-router-dom'; import { isAuth } from '../services/Auth'; // 继承Route内置属性类型,保证私有路由支持所有原生Route属性 interface PrivateRouteProps extends RouteProps { component?: React.ComponentType<Record<string, unknown>>; } export const PrivateRoute = ({ component: Component, ...rest }: PrivateRouteProps) => ( <Route {...rest} render={(props) => isAuth() ? Component ? <Component {...props} /> : null : <Redirect to="/user/login" /> } /> );
关键类型说明
RouteProps是react-router-dom内置的Route组件属性类型,继承后私有路由可直接使用path/exact/strict等所有原生路由属性React.ComponentType是React函数组件和类组件的联合类型,兼容所有合法的React组件入参- 泛型使用
Record<string, unknown>替代any适配严格模式校验,若需要适配路由组件自带的history/location/match属性,可引入RouteComponentProps将类型修改为React.ComponentType<RouteComponentProps> - 新增
Component非空判断,避免入参为空时的渲染异常 - 将原箭头函数的大括号改为小括号实现隐式返回,也可保留大括号后添加
return语句,功能完全一致
内容的提问来源于stack exchange,提问作者Juvenal Bruno Andrade
相关产品推荐
相关产品推荐

