0
votes

I'm trying to use React-redux connect with typescript. I'm confused in using the connect with withRouter.

I'm trying to use it like,

withRouter<any>(connect<{},ComponentProps,{}>(
    matchStateToProps, 
    matchDispatchToProps
)(Component));

When trying to pass property productList it throws,

TS2339: Property 'productList' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes, ComponentState>> & Rea...

But in another component,

withRouter<any>(connect<{}, ComponentProps, {}>(
    mapStateToProps, 
    mapDispatchToProps
)(Component));

Does work just fine. ComponentProps contains all the properties of component. (including stateProps, dispatchProps, RouteProps, & own props).

How to use connect in typescript with react's withRouter? What should I pass as props for withRouter & connect?

2
"doesn't work" Why not? What happened? - underscore_d
@underscore_d I don't have a clue. To be honest, I don't know whether any of the above approach is correct. - Prajwal
I think your approach is correct. There may be another error that has to do with some property 'productList', but I cannot see any of the code for that. - Hinrich

2 Answers

2
votes

I do it this way:

import { compose } from 'redux';

then:

export default compose<React.ComponentClass>(
  withRouter,
  connect<IMapStateToProps, IMapDispatchToProps, IConnectedRouterProps>(
    mapStateToProps,
    {
      fetchComponentData
    },
  ),
)(Component);
0
votes

After some trouble I was able to get this to work!

// assuming all these interfaces are well defined somewhere.
type MyComponentProps = OwnProps & ComposeProps & StateProps & DispatchProps;

// the secret sauce, need to define a class constructor to pass to compose
interface MyComponentClass<MyComponentProps> extends React.ComponentClass {
  new (props: MyComponentProps): React.Component<MyComponentProps>;
}

export class MyComponent extends React.Component<MyComponentProps> {
  ...
}

export default compose<MyComponentClass<MyComponentProps>>(
  withSomeHOC(),
  connect<StateProps, DispatchProps, OwnProps>(mapStateToProps, mapDispatchToProps)
)(MyComponent);

The above will allow you to import the composed component and maintain type safety!