我正在尝试使用 matchPath
从父容器中提取路由参数,如 https://stackoverflow.com/a/45492498/3574819 中所述
const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });
当我 console.log(topicMatch.params)
时,对象设置了 topic
键,但是如果我尝试访问 topicMatch.params.topic
我收到以下错误:
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
是一个采用泛型类型的参数化函数 <P>
并返回与 match<P>
的匹配项. P
由您定义;否则我实际上不确定 TypeScript 如何确定返回类型。
matchPath<{topic: "string"}>(...)
如果您愿意,您也可以创建自己的类型,例如
interface RouteParams {
topic: string;
}
然后做matchPath<RouteParams>(...)
.
关于javascript - 如何为 matchPath 返回值设置 typescript 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47272473/