TypeScript 2.6 introduced strictFunctionTypes
,升级后,我似乎无法让Redux和React路由器与它相互配合。因此,我想知道如何最好地定义要在特定路线上显示的组件的类型,并从Redux接收道具。
以下是关于我如何设置我的应用程序。有这样的路线:
<Route path="/some/path/with/:parameter" component={ConnectedComponent}/>
然后我想要显示的组件从Redux和React路由器接收道具,我试图用以下类型签名捕获:
class BareComponent extends React.Component<ReduxProps & RouteProps, ArbitraryState>
... Redux道具的定义类似于以下内容:
interface StateProps { storeProperty: string; }
interface DispatchProps { dispatchCallback: () => void; }
type ReduxProps = StateProps & DispatchProps;
...和路由器的道具有点像:
interface RouteParams { parameter: string }
type RouteProps = RouteComponentProps<RouteParams>;
(从RouteComponentProps
导入react-router-dom
)
传递给路由器的组件(通过上面第一个代码示例中的Route
)创建如下:
const ConnectedComponent = connect<StateProps, DispatchProps, RouteProps, ArbitraryStateInterface>(mapStateToProps)(BareComponent);
不幸的是,对于strictFunctionTypes
,这会导致TypeScript抱怨ConnectedComponent
无法分配给React Router期望的类型:
TS2322: Type '{ path: "/some/path/with/:parameter"; component: ComponentClass<Pick<StatePr...' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Route> & Readonly<{ children?: ReactNode; }> & Rea...'.
Type '{ path: "/some/path/with/:parameter"; component: ComponentClass<Pick<StatePr...' is not assignable to type 'Readonly<RouteProps>'.
Types of property 'component' are incompatible.
Type 'ComponentClass<Pick<StateProps & DispatchProps & RouteC...' is not assignable to type 'StatelessComponent<RouteComponentProps<any> | undefined> | ComponentClass<RouteComponentProps<any...'.
Type 'ComponentClass<Pick<StateProps & DispatchProps & RouteC...' is not assignable to type 'ComponentClass<RouteComponentProps<any> | undefined>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'RouteComponentProps<any> | undefined' is not assignable to type 'Pick<StateProps & DispatchProps & RouteComponentProps<R...'.
Type 'undefined' is not assignable to type 'Pick<StateProps & DispatchProps & RouteComponentProps<R...'.
Type 'undefined' is not assignable to type 'Pick<StateProps & DispatchProps & RouteComponentProps<R...'.
那么,我定义上述类型的方式与这些类型的使用方式不一致?我是否有办法在不诉诸strictFunctionTypes
s的情况下启用any
?
答案 0 :(得分:0)
除了您已使用的react-router-dom
之外,请尝试使用withRouter
的{{1}} HOC功能。
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md
提示:使用connect
来保持整洁(并且还有助于解决我发现的严格打字稿问题)。
recompose
将'void'替换为您想要曝光的任何道具。
可能是95%。目前没有VPN访问权限进行双重检查。我正在通电话,对不起格式化。我会更新一次,我可以查看哪些对我有用!