Created
October 1, 2020 00:52
-
-
Save icorbrey/4fb720da34c48b57804ab7c222768dca to your computer and use it in GitHub Desktop.
A typechecked action type matcher for reducers
This file contains hidden or 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
type IndexableType = string | number | |
type Action<PossibleTypes extends IndexableType> = { | |
type: PossibleTypes | |
payload: any | |
} | |
type Matchers< | |
PossibleTypes extends IndexableType, | |
PossibleActions extends Action<PossibleTypes>, | |
ReturnType> = { | |
[SelectedType in PossibleTypes]: (payload: Payload< | |
PossibleTypes, | |
PossibleActions, | |
SelectedType | |
>) => ReturnType | |
} | |
type Payload< | |
PossibleTypes extends IndexableType, | |
PossibleActions extends Action<PossibleTypes>, | |
SelectedType extends PossibleTypes> = (PossibleActions & { | |
type: SelectedType | |
})['payload'] | |
export const match = < | |
PossibleTypes extends IndexableType, | |
PossibleActions extends Action<PossibleTypes>, | |
ReturnType> | |
( | |
action: PossibleActions, | |
matchers: Matchers<PossibleTypes, PossibleActions, ReturnType> | |
): ReturnType => | |
matchers[action.type](action.payload) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment