Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to add type parameters for react-redux

Adding Type Parameters to connect

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
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<any> // If you can type your action more precisely, use that type instead of `any`
|};

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
You can’t perform that action at this time.