Skip to content

Instantly share code, notes, and snippets.

@jbrown215
Forked from villesau/react-redux-annotations.md
Last active February 28, 2020 09:30
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbrown215/f425203ef30fdc8a28c213b90ba7a794 to your computer and use it in GitHub Desktop.
Save jbrown215/f425203ef30fdc8a28c213b90ba7a794 to your computer and use it in GitHub Desktop.
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