reselect icon indicating copy to clipboard operation
reselect copied to clipboard

How to Pass Generics to createSelector With Arguments?

Open elsonel opened this issue 8 months ago • 1 comments

export const selectFormValues = createSelector<
  [
    (state: RootState) => RootState['sliceValues'],
    (state: RootState, type: T) => T
  ],
  TypeToFormMap[T]
>(
  [
    (state) => state.sliceValues,
    (state, type) => type,
  ],
  (sliceValues, type) => sliceValues.formValuesMap[type]
);

Where could I define the generic T for something like this?

// Usage:

// TypeToFormMap['goal-form']
const values = useSelector((state: RootState) => selectFormValues(state, 'goal-form')

elsonel avatar Mar 10 '25 08:03 elsonel

due to typescript limitations, reselect selectors cannot be generic (and you shouldn't be passing type parameters to them)

with that said, your example doesn't even need reselect:

export const selectFormValues = <T extends keyof TypeToFormMap>(state: RootState, type: T) => state.sliceValues.formValuesMap[type]

There's nothing being derived, so there's no memoisation needed

EskiMojo14 avatar Mar 10 '25 10:03 EskiMojo14