react-redux-typescript-guide icon indicating copy to clipboard operation
react-redux-typescript-guide copied to clipboard

suggestion: add info about dispatched action types

Open arolson101 opened this issue 7 years ago • 5 comments

When declaring a connected component's property types I find it helpful to use the typeof operator to declare dispatched function types so that the property matches the action's declaration:

const actions = {
  ping: createAction('ping/PING', (arg: number) => ({
    type: 'ping/PING',
    arg,
  })),
};

interface Props {
  ping: typeof actions.ping;
}

const PingTestComponent: React.SFC<Props> = ({ping}) => {
  return (
    <Button onPress={() => ping(123)} title="ping"/>
  );
};

export const PingTest = connect(
  null,
  ({ ping: actions.ping })
)(PingTestComponent);

arolson101 avatar Jan 19 '18 19:01 arolson101

I agree that sometime it make sense, especially when you declare your component and connect in the same file, but it also makes a component more coupled to the actions, so I'm not really convinced to recommend it as a good practice but rather I think of it as a developer preference

piotrwitek avatar Jan 20 '18 20:01 piotrwitek

@boostio funded this issue with $25. Visit this issue on Issuehunt

IssueHuntBot avatar Sep 15 '18 04:09 IssueHuntBot

@issuehuntfest has funded $15.00 to this issue. See it on IssueHunt

IssueHuntBot avatar Dec 03 '18 09:12 IssueHuntBot

After some consideration I think it would be good to add it to the guide, especially in case when you don't care about tightly coupling your components to actions then it can be really beneficial because there will be less manual maintenance of types declarations and much better error reporting (at Props type declaration instead of more complex error at connect location).

piotrwitek avatar Dec 03 '18 19:12 piotrwitek

By the way, the dispatchProps return type would be the return type of the action creator. Was this supposed to be void instead?

interface Props {
  ping: typeof actions.ping;
}

Shouldn't be derived as below from the types?

 interface Props {
   ping: (arg: number) => void
}

veeramarni avatar May 26 '19 12:05 veeramarni