How to set typescript type for matchPath return value

允我心安 提交于 2020-12-12 06:06:41

问题


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>
            );
        }
    }
);

回答1:


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, e.g.

interface RouteParams {
  topic: string;
}

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



来源:https://stackoverflow.com/questions/47272473/how-to-set-typescript-type-for-matchpath-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!