Skip to content

Instantly share code, notes, and snippets.

@villesau
Last active April 8, 2019 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save villesau/38ec8c821e9ba4062e1ee35d841890d4 to your computer and use it in GitHub Desktop.
Save villesau/38ec8c821e9ba4062e1ee35d841890d4 to your computer and use it in GitHub Desktop.
How to add type parameters for react-redux

This suppress was added due to the high amount of type errors after updating Flow and adding the most recent libdefs for react-redux.

Take ownership of the code you've written and add the type parameters

For react-redux it's usually enough to add types for Props and OwnProps.

Before:

type Props = {
  item: Array<Item>,
  otherItems: Array<OtherItem>,
  value?: string,
  onChange: (itemId: string) => void,
  openModal: (item: Item) => void
};

export const Component = (props: Props) => <div/>

const mapStateToProps = (state: State) => ({
  otherItems: getOtherItems(state)
});

// $FlowSuppress https://bit.ly/2Uvi2uU
export default connect(mapStateToProps)(Component);

After:

type OwnProps = {|
  item: Array<Item>,
  value?: string,
  onChange: (itemId: string) => void,
  openModal: (item: Item) => void
|};

type StateProps = {| otherItems: $ReadOnlyArray<OtherItem> |};

type Props = {|
  ...OwnProps,
  ...StateProps,
  dispatch: Dispatch<*>
|};

export const Component = (props: Props) => <div/>

const mapStateToProps = (state: State): StateProps => ({
  otherItems: getOtherItems(state)
});

export default connect<Props, OwnProps, _, _, _, _>(mapStateToProps)(
  Component
);

OwnProps are the props passed from the outside world to ConnectedComponent, and Props are the props that ConnectedComponent passes to WrappedComponent. This means that Props should usually contain all the fields in OwnProps and new fields added by the connect() prop mappers (mapStateToProps etc).

More resources

Libdefs: https://github.com/flow-typed/flow-typed/blob/master/definitions/npm/react-redux_v5.x.x/flow_v0.89.x-/react-redux_v5.x.x.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment