redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

`listenerMiddleware` type error in matcher using custom actions.

Open antondalgren opened this issue 1 year ago • 3 comments

I have a codebase using legacy redux patterns and trying to slowly but steadily transition to using modern redux. I have a set of old Actions that are created similiar to ExtraAction mentioned below. When using the listenerMiddleware to add a set of type guards as matchers using the isAnyOf utility as demonstrated below, I see a type error on the matcher.

~~Also, it seems as the type inferred from the predicate (probably the matcher to) doesn't carry along into effect callback.~~

    interface ExtraAction extends Action {
      payload: number
    }

    function isPayloadAction(action: any): action is ExtraAction {
      return (
        isFluxStandardAction(action) && typeof action.payload === 'number'
      )
    }

    startListening({
      matcher: isAnyOf(isPayloadAction),
      effect: (action, listenerApi) => {
        expectTypeOf(action).toMatchTypeOf<ExtraAction>()
      },
    })

antondalgren avatar Sep 24 '24 10:09 antondalgren

predicate isn't used as a type guard, only matcher is.

Could you post what the type error you're getting is?

https://github.com/reduxjs/redux-toolkit/issues/3862 is also likely related.

EskiMojo14 avatar Sep 24 '24 11:09 EskiMojo14

predicate isn't used as a type guard, only matcher is.

Could you post what the type error you're getting is?

#3862 is also likely related.

Thank you for the swift response.

Here is the ts-error:

No overload matches this call.
  The last overload gave the following error.
    Type '(action: any) => action is ActionMatchingAnyOf<[(action: any) => action is ExtraAction]>' is not assignable to type 'undefined'.ts(2769)
types.ts(489, 7): The expected type comes from property 'matcher' which is declared here on type '{ actionCreator?: undefined; type?: undefined; matcher?: undefined; predicate: AnyListenerPredicate<unknown>; effect: ListenerEffect<UnknownAction, unknown, ThunkDispatch<unknown, unknown, UnknownAction>, unknown>; }'
types.ts(485, 3): The last overload is declared here.

This does provide action with the correct type, thus using a type guard as predicate should carry along the correct type, shouldn't it? 🤔

    startListening({
      predicate: incrementByAmount.match,
      effect: (action, listenerApi) => {
        expectTypeOf(action).toMatchTypeOf<ExtraAction>()
      },
    })

antondalgren avatar Sep 24 '24 11:09 antondalgren

No, predicate explicitly does not narrow the action type. It's a very generic (action, prevState, nextState) => boolean callback that could have any logic inside, and so it can't guarantee the type of action.

markerikson avatar Sep 24 '24 11:09 markerikson

No, predicate explicitly does not narrow the action type. It's a very generic (action, prevState, nextState) => boolean callback that could have any logic inside, and so it can't guarantee the type of action.

OK. The explanation of the issue still holds for matchers. Any suggestions on how I could fix this in either a PR or a workaround in my codebase?

antondalgren avatar Oct 30 '24 08:10 antondalgren

have you checked out the issue i linked, and tried moving the isAnyOf call to a separate variable like the replies to that issue recommend?

EskiMojo14 avatar Oct 30 '24 10:10 EskiMojo14

have you checked out the issue i linked, and tried moving the isAnyOf call to a separate variable like the replies to that issue recommend?

Yes, just tried and that didn't help. It works as expected when using RTK defined actions such as below. But not when using custom built matcher functions.

const myThunk = createAsyncThunk.....;

const myMatcher = isAnyOf(myThunk.fulfilled),
startListening({
   matcher: myMatcher,
   effect: (action, listenerApi) => {
     expectTypeOf(action).toMatchTypeOf<typeof myThunk....>()
   },
})

antondalgren avatar Nov 15 '24 07:11 antondalgren

Could you put together a reproduction of this, either in Typescript Playground or a repo i can checkout?

EskiMojo14 avatar Nov 15 '24 10:11 EskiMojo14

Could you put together a reproduction of this, either in Typescript Playground or a repo i can checkout?

Sure, here is a commit adding a testcase in a fork of this repo. Hope this is clear enough, otherwise let me know and I'll try to adjust! https://github.com/antondalgren/redux-toolkit/commit/de72aace213a44e4223fe9b89867346de9c5c65e

antondalgren avatar Nov 15 '24 20:11 antondalgren

ok, that helped a little - it still won't work inline because of the TS bug mentioned previously, but i found a change that fixes it when the predicate is defined outside.

Switching from UnknownAction to Action works:

index b5980e10..eb42c86b 100644
--- a/packages/toolkit/src/listenerMiddleware/types.ts
+++ b/packages/toolkit/src/listenerMiddleware/types.ts
@@ -466,7 +466,7 @@ export type AddListenerOverloads<
   ): Return
 
   /** Accepts an RTK matcher function, such as `incrementByAmount.match` */
-  <MatchFunctionType extends MatchFunction<UnknownAction>>(
+  <MatchFunctionType extends MatchFunction<Action>>(

Presumably this is because any interface is missing the index signature UnknownAction has. you can verify this by switching ExtraAction to a type instead and the error disappears: Image

This is briefly covered in this article by Matt Pocock.

EskiMojo14 avatar Nov 15 '24 23:11 EskiMojo14

Oh, so the preferred way of declaring actions in a legacy type of application would be to use type instead of interface? Well, today I learned something new. Thank you for taking the time to look through this issue @EskiMojo14 !

antondalgren avatar Nov 21 '24 14:11 antondalgren