reduxjs / react-redux

Official React bindings for Redux
https://react-redux.js.org
MIT License
23.35k stars 3.38k forks source link

useSelector doesn't infer selector types properly with shallowEqual #2186

Open NestlyS opened 2 months ago

NestlyS commented 2 months ago

What version of React, ReactDOM/React Native, Redux, and React Redux are you using?

What is the current behavior?

I got a type error after updating to react-redux 9.1.2 from 7.1.33, so there were no errors at 7.1.33. It's simple. When I use shallowEqual in useSelector, useSelector returns any type.

It reproduces, when I use useSelector directly or via

export const useAppSelector = useSelector.withTypes<IAppState>();

In the example below, editors would be of type any.

const editors = useAppSelector(selectEditorsActive, shallowEqual);

Even if the selector has a type declaration

image

And if I delete shallowEqual as the second argument everything will be fine.

const editors = useAppSelector(selectEditorsActive);

Right now I use next code for correct type checking

export const useAppSelector: TypedUseSelectorHook<IAppState> = useSelector;

I tried to make a demo with bug, but there is no bug in clean project https://codesandbox.io/p/sandbox/polished-breeze-v2dmxw?file=%2Fsrc%2Fhooks.ts%3A4%2C55

What is the expected behavior?

I can use useSelector.withTypes with shallowEqual, without any need in TypedUseSelectorHook.

Which browser and OS are affected by this issue?

None, it's type error

Did this work in previous versions of React Redux?

damonaskavio commented 2 weeks ago

I managed to get it working on mine by returning the shallowEqual function in an arrow function instead of just passing in shallowEqual as an arg.

const editors = useAppSelector(selectedEditorsActive, (a, b) => shallowEqual(a, b));