Created
December 11, 2022 06:07
-
-
Save carlgieringer/d87bc682e0d9e7a74b7175f167fe3f30 to your computer and use it in GitHub Desktop.
A helper for matching multiple redux action creators producing a typed action.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AnyAction, ActionCreatorWithPreparedPayload } from "@reduxjs/toolkit"; | |
/** | |
* A helper for matching multiple redux action creators producing a typed action. | |
* | |
* Usage: | |
* | |
* ``` | |
* export default createReducer(initialState, builder => { | |
* builder.addMatcher( | |
* matchActions( | |
* api.login.response, | |
* api.confirmRegistration.response, | |
* api.confirmPasswordReset.response, | |
* ), | |
* (state, action) => { | |
* // action.payload type is inferred! | |
* state.authToken = action.payload.authToken | |
* }, | |
* ) | |
* }) | |
* ``` | |
*/ | |
export function matchActions< | |
T1 extends ActionCreatorWithPreparedPayload<any[], any>, | |
T2 extends ActionCreatorWithPreparedPayload<any[], any>, | |
T3 extends ActionCreatorWithPreparedPayload<any[], any>, | |
T4 extends ActionCreatorWithPreparedPayload<any[], any>, | |
T5 extends ActionCreatorWithPreparedPayload<any[], any> | |
>(ac1: T1, ac2: T2, ac3?: T3, ac4?: T4, ac5?: T5) { | |
return function actionMatcher( | |
action: AnyAction | |
): action is ReturnType<T1> & | |
ReturnType<T2> & | |
ReturnType<T3> & | |
ReturnType<T4> & | |
ReturnType<T5> { | |
return ( | |
ac1.match(action) || | |
ac2.match(action) || | |
(ac3 && ac3.match(action)) || | |
(ac4 && ac4.match(action)) || | |
(!!ac5 && ac5.match(action)) | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment