Typescript向React组件透传rest props报属性不存在错误如何解决
问题原因
TypeScript的类型校验发生在编译阶段,你在运行时通过解构语法将未显式声明的属性归入rest变量的逻辑,不会影响编译阶段的类型检查。你当前定义的WiseRouterProps接口仅包含了你显式列出的属性,没有声明其他属性的合法性,因此传入exact、path等未定义的属性时会触发类型报错。
另外你接口中定义的rest: [] | null | undefined属于无效声明,它代表组件接收一个名为rest的prop,和你解构生成的rest变量完全无关,这个字段可以直接删除。
可行解决方案
方案1:继承react-router的RouteProps类型(推荐)
由于你透传的属性都是react-router-dom中Route组件支持的属性,直接继承RouteProps的类型即可获得完整的类型校验和提示:
import { RouteProps } from 'react-router-dom'; interface WiseRouterProps extends RouteProps { component: React.ComponentType<any> | null | undefined, needsAuthentication: boolean | undefined, needsAuthorisation: boolean | undefined, isAuthenticated: boolean | undefined, isAuthorised: boolean | undefined, userPermissions: string[] | undefined, routePermissions: string[] | undefined, redirectTo: string | null | undefined, defaultRedirect: string | '/' | undefined, fallback: null | Fallback | undefined, debug: boolean | undefined, passRouteProps: boolean | string[] | undefined, }
该方案的优势是所有Route组件支持的属性都会自动获得类型校验,传错属性时TS会及时提示,适配你的业务场景。
方案2:添加索引签名支持任意透传属性
如果你需要支持传入任意未显式声明的属性,可以给接口添加索引签名:
interface WiseRouterProps { component: React.ComponentType<any> | null | undefined, needsAuthentication: boolean | undefined, needsAuthorisation: boolean | undefined, isAuthenticated: boolean | undefined, isAuthorised: boolean | undefined, userPermissions: string[] | undefined, routePermissions: string[] | undefined, redirectTo: string | null | undefined, defaultRedirect: string | '/' | undefined, fallback: null | Fallback | undefined, debug: boolean | undefined, passRouteProps: boolean | string[] | undefined, // 索引签名,允许任意字符串类型的属性 [key: string]: any; }
该方案灵活性更高,但会丢失透传属性的类型校验,传入错误属性TS不会报错。
两种方案修改完成后,你原本的解构和透传逻辑不需要做任何调整,即可解决类型报错问题。
内容的提问来源于stack exchange,提问作者coredumped0x
相关产品推荐
相关产品推荐

