Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何设置matchPath返回值的typescript类型_Javascript_Typescript_React Router_React Router Dom - Fatal编程技术网

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