TypeScript 2.6 引入了
下面是我如何设置我的应用程序。有这样一个路由:
strictFunctionTypes
。在升级后,我似乎无法让Redux和React Router正常工作并互相配合。因此,我想知道如何最好地定义一个组件的类型,该组件既要显示在某个路由上,又要从Redux接收props。下面是我如何设置我的应用程序。有这样一个路由:
<Route path="/some/path/with/:parameter" component={ConnectedComponent}/>
然后,我希望显示的组件从Redux和React Router接收props,以下是我尝试捕获的类型签名:
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...'.
那么,我上面定义类型的方式有什么不符合类型使用方式的地方吗?有没有办法在不使用 any
的情况下启用 strictFunctionTypes
?
withRouter
,但我不认为它解决了我的问题?据我所知,withRouter
只是将路由器的 props 传递给连接的组件,但是<Route>
(它被传递到其中)不是也做同样的事情吗?为什么<Route>
(或其类型定义)会期望一个被withRouter
包装的组件呢? - Vincent