如何为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<{}>(类 App 扩展了 React.Component, AuthState>{使成为() {const { 历史} = this.props;const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });如果(主题匹配){控制台日志(topicMatch.params);//有主题键控制台日志(topicMatch.params.topic);//导致编译错误}返回 (<div className="应用程序"><div className="App-header"><img src={logo} className="App-logo" alt="logo"/><h2>欢迎反应</h2>
);}});
matchPath
是一个参数化函数,它接受一个泛型类型 并返回一个与
匹配
.P
由你来定义;否则我实际上不确定 TypeScript 如何确定返回类型.
matchPath<{topic: "string"}>(...)
如果您愿意,您也可以创建自己的类型,例如
interface RouteParams {主题:字符串;}
然后执行matchPath
.
I'm trying to use matchPath
to extract a route param from the parent container as described in https://stackoverflow.com/a/45492498/3574819
const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });
When I console.log(topicMatch.params)
, the object has the topic
key set but if I try to access topicMatch.params.topic
I get the following error:
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
is a parameterized function that takes a generic type <P>
and returns a match with match<P>
. It's up to you to define P
; otherwise I'm actually not sure how TypeScript determines the return type.
matchPath<{topic: "string"}>(...)
You could also create your own type if you wish, e.g.
interface RouteParams {
topic: string;
}
and then do matchPath<RouteParams>(...)
.
这篇关于如何为matchPath返回值设置打字稿类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!