Skip to content

Instantly share code, notes, and snippets.

@icorbrey
Created October 1, 2020 00:52
Show Gist options
  • Save icorbrey/4fb720da34c48b57804ab7c222768dca to your computer and use it in GitHub Desktop.
Save icorbrey/4fb720da34c48b57804ab7c222768dca to your computer and use it in GitHub Desktop.
A typechecked action type matcher for reducers
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