【问题标题】:How to set typescript type for matchPath return value如何为 matchPath 返回值设置打字稿类型
【发布时间】:2018-04-26 14:47:00
【问题描述】:

我正在尝试使用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>
            );
        }
    }
);

【问题讨论】:

    标签: javascript typescript react-router react-router-dom


    【解决方案1】:

    matchPath 是一个参数化函数,它采用泛型类型&lt;P&gt; 并返回与match&lt;P&gt; 的匹配项。由您来定义P;否则我实际上不确定 TypeScript 是如何确定返回类型的。

    matchPath<{topic: "string"}>(...)
    

    如果您愿意,您也可以创建自己的类型,例如

    interface RouteParams {
      topic: string;
    }
    

    然后执行matchPath&lt;RouteParams&gt;(...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-29
      • 2021-09-18
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 2015-08-10
      相关资源
      最近更新 更多