问题
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