简体   繁体   中英

How to set typescript type for matchPath return value

I'm trying to use matchPath to extract a route param from the parent container as described in https://stackoverflow.com/a/45492498/3574819

const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });

When I console.log(topicMatch.params) , the object has the topic key set but if I try to access topicMatch.params.topic I get the following error:

error TS2339: Property 'topic' does not exist on type '{}'.

const RouterApp = withRouter<{}>(
    class App extends React.Component<RouteComponentProps<{}>, AuthState> {
        render() {
            const { history } = this.props;    
            const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });

            if (topicMatch) {
                console.log(topicMatch.params); // has topic key
                console.log(topicMatch.params.topic); // causes compile error
            }

            return (
                <div className="App">
                    <div className="App-header">
                        <img src={logo} className="App-logo" alt="logo"/>
                        <h2>Welcome to React</h2>
                    </div>
                </div>
            );
        }
    }
);

matchPath is a parameterized function that takes a generic type <P> and returns a match with match<P> . It's up to you to define P ; otherwise I'm actually not sure how TypeScript determines the return type.

matchPath<{topic: "string"}>(...)

You could also create your own type if you wish, eg

interface RouteParams {
  topic: string;
}

and then do matchPath<RouteParams>(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM