This’ll be a quick post about how to fix most of the connect
annotations.
Upgrading Flow past 0.85 has been tough. Flow asks for more required annotations after 0.85 created some hundreds of errors requiring for annotations. And what has dragged me the most is mainly connect
and (especially together with) some other higher order components.
Annotating the most common use case of connect
Namely, the use case of connect
with a mapStateToProps
and the the object shorthand of mapDispatchToProps
:
FlowTyped to react-redux_v5.x.x/flow_v0.89.x-
First, update flow-typed
definitions for react-redux
to the v0.89.x version. This contains the latest support for the bug fix in Flow 0.85 which required us to explicitly pass types into the exported generic types. To learn more, you may read the pull request #3012.
The connect
declaration decrypted
connect
will have six type parameters
connect<-P, -OP, -SP, -DP, S, D>
Decrypting to:
connect<Props, OwnProps, StateProps, DispatchProps, State, Dispatch>
Not all of those type parameters are required. You may replace part of those with a placeholder _
. But you may not omit the placeholders.
How to annotate
- Annotate the return of
mapStateToProps
- Annotate
Props
andOwnProps
type parameters forconnect
-
Props
is normally the prop types for the component -
OwnProps
normally isProps
minus those fed in byconnect
viamapStateToProps
andmapDispatchToProps
// react-redux_v5.x.x/flow_v0.89.x-/test_connect.js
type OwnProps = {|
passthrough: number,
forMapStateToProps: string,
forMapDispatchToProps: string,
|}
type Props = {
...OwnProps,
fromMapDispatchToProps: string,
fromMapStateToProps: string,
}
type State = { a: number }
type MapStateToPropsProps = { forMapStateToProps: string }
const mapState = (state: State, props: MapStateToPropsProps) => {
return {
fromMapStateToProps: 'str' + state.a,
}
}
const mapDispatch = {
dispatch1: (num: number) => {},
dispatch2: () => {},
}
connect<Props, OwnProps, _, _, _, _>(mapState, mapDispatch)(MyComponent)
Where to learn more?
I saw this question asked in Flow’s GitHub repo if not at a lot more places. I had a hard time trying to figure it out myself, too.
Is there an "official way" of annotating
connect
?
Short answer: no.
A bit longer answer as suggested in the first reply in #7493:
Have a look at the tests alongside the flow-typed libdef. That's the best way to see up-to-date recommended practices.
Top comments (0)