TypeScript 2.6 introduced strictFunctionTypes
,升级后,我似乎无法让Redux和React Router与它们相互配合。因此,我想知道如何最好地定义要在特定路线上显示的组件的类型,并从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
?
除了你已经使用的react-router-dom
之外,尝试使用withRouter
的connect
HOC功能。 https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md
提示:使用recompose
来保持整洁(并且还有助于我发现严格的打字稿头痛)。
import { withRouter } from 'react-router-dom';
import { compose } from 'recompose';
...
...
export const ConnectedComponent = compose<ReduxProps & RouteProps, void>(
connect(mapStateToProps, mapDispatchToProps),
withRouter
)(BareComponent);
将'void'替换为您想要暴露的任何道具。
这可能是其中的95%。目前没有VPN访问权限进行双重检查。我正在通电话,对不起格式化。我会更新一次,我可以查看哪些对我有用!