The useSelector
hook has two generic variables: the type of the overall state (TState
) and the type of the selected value (TSelected
). Our goal is to create a bound hook where TState
is fixed, but TSelected
changes based on the selector argument we use with the hook.
TypedUseSelectorHook
serves as a typescript override. Essentially, your useTypedSelector
simply becomes useSelector
.
In contrast, createSelectorHook
works differently as it is a factory function that generates a useSelector
hook. It accepts an optional context argument (docs link) and another generic variable for Action
, as the context hinges on the action type. Since your selector hook does not rely on the action type, you can ignore this. The Action
variable is optional and defaults to AnyAction
. You only need to specify the generic for the state:
export const useTypedSelector = createSelectorHook<RootState>();
The type definition for useTypedSelector
aligns with expectations, featuring a hook with just one generic representing the selected value:
const useTypedSelector: <Selected extends unknown>(
selector: (state: RootState) => Selected,
equalityFn?: ((previous: Selected, next: Selected) => boolean) | undefined
) => Selected
Playground Link