Florian Kuc
Florian Kuc

Reputation: 147

Typescript HOC with redux connect

I am trying create a HOC with redux' connect wrapping some other component. However I cannot seem to get the arguments of the connect generic right. Other guides on this topic I found have either barely scratched the surface or are going right over my head. I would appreciate some help on this. This is my code so far:

import React, { ReactElement } from 'react'
import {StoreState} from '../reducers'
import {connect} from 'react-redux'

interface Props{
  auth: boolean
}

interface OwnProps {

}

export default (ChildComponent: React.ComponentType): React.ComponentType<typeof ChildComponent>=> {
  class ComposedComponent extends React.Component<Props> {

  componentDidMount(): void{
    this.shouldNavigateAway()
  }

  componentDidUpdate(): void {
    this.shouldNavigateAway()
  }

  shouldNavigateAway = (): void => {
    if (!this.props.auth) {
      //do something
    }
  }

    render(): ReactElement {
      return <ChildComponent {...this.props} />
    }
  }

  const mapStateToProps = ({
    auth,
  }: StoreState): {auth: boolean} => {
    return { auth }
  }

  return connect<Props, {}, OwnProps>(mapStateToProps)(ComposedComponent)
}

The error I am getting is solely on the 'mapStateToProps' in my return statement at the very end and it says:

const mapStateToProps: ({ auth, }: StoreState) => {
    auth: boolean;
}
Argument of type '({ auth, }: StoreState) => { auth: boolean; }' is not assignable to parameter of type 'MapStateToPropsParam<Props, OwnProps, DefaultRootState>'.
  Type '({ auth, }: StoreState) => { auth: boolean; }' is not assignable to type 'MapStateToPropsFactory<Props, OwnProps, DefaultRootState>'.
    Types of parameters '__0' and 'initialState' are incompatible.
      Type 'DefaultRootState' is missing the following properties from type 'StoreState': comments, authts(2345)

My StoreState interface looks as follows:

export interface StoreState {
  comments: Comment[]
  auth: boolean
}

However I feel like I do need its return type the way it is. I have already tried omitting the comments part of my state since the HOC is only responsible for the auth property but in that case the error will still complain that 'auth' is missing. Kinda stuck here and not sure where TS is trying to point me.

Upvotes: 1

Views: 1741

Answers (1)

markerikson
markerikson

Reputation: 67539

Per the React-Redux usage guide page on "Static Typing", you actually shouldn't be trying to declare the generics in connect directly. In fact, we specifically recommend using the ConnectedProps<T> technique described in that page to automatically infer the type of all the props being passed from connect to your own component.

Upvotes: 2

Related Questions