React TypeScript新手遇类型错误:{ match: any; }不兼容RouteComponentProps
Hey there! Let's sort out this type error you're hitting with your React + TypeScript code. The issue comes down to how you're annotating the match prop in your Route's render function, plus you don't need to redefine the route match interface—React Router already provides a built-in type for that.
What's Going Wrong?
Your line:
<Route path={"/sch/:schProd"} render={({ match: faceMatch<{ schProd: string }>}) => <Home match={match}/>} />
has a syntax mistake: when you write match: faceMatch<{ schProd: string }> inside the destructured parameters, TypeScript interprets this as renaming the match variable (not adding a type annotation). That leaves the original match variable untyped (treated as any), which clashes with React Router's expected type for the render callback.
Plus, you don't need to define your own faceMatch interface—React Router exports RouteComponentProps which covers exactly this structure (params, isExact, path, url).
Step-by-Step Fix
Import the built-in type from
react-router-dom:
Make sure you're importingRouteComponentPropsalong with your other router imports.Correct the
Routerender callback type annotation
Instead of trying to type the destructured variable directly, annotate the entire props object withRouteComponentProps, specifying your params type as the generic argument.Update the
Homecomponent's props type
UseRouteComponentPropsinstead of your customfaceMatchinterface to align with React Router's types.
Fixed Code Example
import React, { FC } from 'react'; import { Router, Route, Link, RouteComponentProps } from 'react-router-dom'; // Note: If you're using BrowserRouter instead of Router, import that instead // No need for your custom faceMatch interface—RouteComponentProps covers it function App() { return ( <Router> <div> <Link to="/sch/h">2</Link> {/* Correctly type the render callback props */} <Route path="/sch/:schProd" render={({ match }: RouteComponentProps<{ schProd: string }>) => ( <Home match={match} /> )} /> </div> </Router> ); } // Use RouteComponentProps for Home's props type const Home: FC<RouteComponentProps<{ schProd: string }>> = ({ match }) => { // Now you can safely access match.params.schProd with proper typing! return ( <div> 100 - Product: {match.params.schProd} </div> ); }; export default App;
Why This Works
RouteComponentProps<{ schProd: string }>tells TypeScript exactly what shape the route props (includingmatch) should have, withschProdtyped as a string inmatch.params.- The destructuring
({ match })now correctly pulls the typedmatchprop from the route props, so TypeScript doesn't treat it asanyanymore. - This aligns your code with React Router's official type definitions, avoiding mismatches and giving you proper autocompletion for route props.
内容的提问来源于stack exchange,提问作者Edgar

