Javascript 如何设置matchPath返回值的typescript类型
我正在尝试使用Javascript 如何设置matchPath返回值的typescript类型,javascript,typescript,react-router,react-router-dom,Javascript,Typescript,React Router,React Router Dom,我正在尝试使用matchPath从父容器中提取路由参数,如中所述 当我console.log(topicMatch.params)时,对象设置了topic键,但如果我尝试访问topicMatch.params.topic我会遇到以下错误: 错误TS2339:类型“{}”上不存在属性“topic” const RouterApp=withRouter( 类应用程序扩展了React.Component{ render(){ const{history}=this.props; const topic
matchPath
从父容器中提取路由参数,如中所述
当我console.log(topicMatch.params)
时,对象设置了topic
键,但如果我尝试访问topicMatch.params.topic
我会遇到以下错误:
错误TS2339:类型“{}”上不存在属性“topic”
const RouterApp=withRouter(
类应用程序扩展了React.Component{
render(){
const{history}=this.props;
const topicMatch=matchPath(history.location.pathname,{path:'/:topic'});
如果(topicMatch){
console.log(topicMatch.params);//具有主题键
console.log(topicMatch.params.topic);//导致编译错误
}
返回(
欢迎反应
);
}
}
);
匹配路径
是一个参数化函数,它采用泛型类型,并返回与匹配
的匹配。由您定义P
;否则,我实际上不确定TypeScript如何确定返回类型
matchPath<{topic: "string"}>(...)
然后执行匹配路径(…)
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<{topic: "string"}>(...)
interface RouteParams {
topic: string;
}