我正在尝试将反应路由器与 TypeScript 一起使用。但是,我在使用 withRouter 函数时遇到了一些问题。在最后一行,我遇到了非常奇怪的错误:
Argument of type 'ComponentClass<{}>' is not assignable to parameter of type 'StatelessComponent<RouteComponentProps<any>> | ComponentClass<RouteComponentProps<any>>'.
Type 'ComponentClass<{}>' is not assignable to type 'ComponentClass<RouteComponentProps<any>>'.
Type '{}' is not assignable to type 'RouteComponentProps<any>'.
Property 'match' is missing in type '{}’
代码如下:
import * as React from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps, withRouter } from 'react-router-dom';
interface HomeProps extends RouteComponentProps<any> {
}
interface HomeState { }
class Home extends React.Component<HomeProps, HomeState> {
constructor(props: HomeProps) {
super(props);
}
public render(): JSX.Element {
return (<span>Home</span>);
}
}
const connectModule = connect(
(state) => ({
// Map state to props
}),
{
// Map dispatch to props
})(Home);
export default withRouter(connectModule);
原文由 Haris Bašić 发布,翻译遵循 CC BY-SA 4.0 许可协议
我使用不同的方法来解决这个问题。我总是将不同的属性(路由器、常规和分派)分开,因此我为我的组件定义了以下接口:
您现在可以创建一个将所有属性组合到一个类型中的新类型,但我总是在组件定义期间组合这些类型(我不在此处添加状态,但如果您需要,请继续)。组件定义如下所示:
现在我们需要通过容器将组件连接到状态。它看起来像这样:
此方法允许完全类型化连接,因此组件和容器是完全类型化的,重构它是安全的。唯一对重构不安全的是路由中映射到
HomeRouterProps
接口的参数。