繁体   English   中英

如何为matchPath返回值设置打字稿类型

[英]How to set typescript type for matchPath return value

我正在尝试使用matchPath从父容器中提取路由参数,如https://stackoverflow.com/a/45492498/3574819中所述

const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });

当我console.log(topicMatch.params) ,该对象已设置了topic密钥,但是如果尝试访问topicMatch.params.topic出现以下错误:

错误TS2339:类型“ {}”上不存在属性“主题”。

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>(...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM