Pass component with arbirtrary/generic props to react-redux connect function in TypeScript
Update: Here's an approach that avoids the initial cast to any
. Now I'm casting the props passed to ConnectedComponent
instead. Investigating the type issue there might reveal whether there are more potential issues than the one I mentioned.
What you're doing is not sound. If Props
were { someState: string }
, your UnconnectedComponent
would be expecting its someState
prop to be a string
, but it would be a number
.
If stateProps
and dispatchProps
should override ownProps
, which is what your code is doing now, I'm not sure whether you're going to be able to get the types to work automatically the way you want. TypeScript can't figure out that the following is sound:
function a<Props>(
b: { [K in keyof Props]: K extends keyof StoreState ? StoreState[K] : Props[K] }
): Omit<Props, keyof StoreState>
{
return b;
}
Maybe you should bite the bullet and use any
. Here's a sample of how you might try to make the caller-facing types safer.
If you instead want ownProps
to override stateProps
, you would want to provide a mergeProps
argument to connect
.
However, be warned that when you create a ReactElement
via JSX, the type
field has type any
, which of course won't give you type safety if you then call createComponent
.