Skip to content

Commit 50093eb

Browse files
committed
fix(useSelector): add NoInfer to equality fn in UseSelector type (reduxjs#2186)
1 parent dc531f4 commit 50093eb

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

src/hooks/useSelector.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,9 @@ export interface UseSelector<StateType = unknown> {
9090
*/
9191
<TState extends StateType = StateType, Selected = unknown>(
9292
selector: (state: TState) => Selected,
93-
equalityFnOrOptions?: EqualityFn<Selected> | UseSelectorOptions<Selected>,
93+
equalityFnOrOptions?:
94+
| EqualityFn<NoInfer<Selected>>
95+
| UseSelectorOptions<NoInfer<Selected>>,
9496
): Selected
9597

9698
/**

test/typetests/hooks.test-d.tsx

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,29 @@ describe('type tests', () => {
100100
const selected2 = useAppSelector((state) => state.stateProp, shallowEqual)
101101

102102
expectTypeOf(selected2).toBeString()
103+
104+
// https://github.com/reduxjs/react-redux/issues/2186
105+
// The equality function must not be an inference site for `Selected`,
106+
// otherwise `shallowEqual`'s `any` parameters widen the result to `any`.
107+
108+
// Selector declared separately (rather than inline) with `withTypes`.
109+
const selectStateProp = (state: TestState) => state.stateProp
110+
111+
const selected3 = useAppSelector(selectStateProp, shallowEqual)
112+
113+
expectTypeOf(selected3).toBeString()
114+
115+
// Selector declared separately with plain `useSelector`.
116+
const selected4 = useSelector(selectStateProp, shallowEqual)
117+
118+
expectTypeOf(selected4).toBeString()
119+
120+
// `shallowEqual` passed via the options object.
121+
const selected5 = useAppSelector((state) => state.stateProp, {
122+
equalityFn: shallowEqual,
123+
})
124+
125+
expectTypeOf(selected5).toBeString()
103126
})
104127

105128
test('useDispatch', () => {

0 commit comments

Comments
 (0)