Last active
July 8, 2021 20:08
-
-
Save fostyfost/21e142d5e58da86bcb2b690588ae5d3b to your computer and use it in GitHub Desktop.
Redux Action Helper
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
import type { ActionsUnion } from '@/store/action-helper' | |
import { createAction } from '@/store/action-helper' | |
export enum StoreActionType { | |
HYDRATE = '@@store/HYDRATE', | |
} | |
export const StoreAction = { | |
hydrate(payload: Record<string, unknown>) { | |
return createAction(StoreActionType.HYDRATE, payload) | |
}, | |
} | |
export type StoreActionsUnion = ActionsUnion<typeof StoreAction> |
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
import type { Action as ReduxAction } from 'redux' | |
// Borrowed from the rex-utils libraryMartin Hochel | |
export interface Action<T> extends ReduxAction<T> { | |
/** | |
* The meta property for the action (see Flux Standard Actions) | |
*/ | |
meta?: { [key: string]: any } | |
} | |
/** | |
* A better typing for the Redux Action | |
*/ | |
export interface ActionWithPayload<T extends string, P> extends Action<T> { | |
/** | |
* The payload of this action | |
*/ | |
payload: P | |
} | |
/** | |
* Create a new action with type and payload | |
*/ | |
export function createAction<T extends string>(type: T): Action<T> | |
export function createAction<T extends string, P>( | |
type: T, | |
payload: P, | |
meta?: { [key: string]: string }, | |
): ActionWithPayload<T, P> | |
export function createAction<T extends string, P>(type: T, payload?: P, meta?: { [key: string]: string }) { | |
return { type, payload, meta } | |
} | |
type ActionsCreatorsMapObject = { | |
[actionCreator: string]: (...args: any[]) => any | |
} | |
export type ActionsUnion<A extends ActionsCreatorsMapObject> = ReturnType<A[keyof A]> | |
export type ActionsOfType<ActionsUnion, ActionType extends string> = ActionsUnion extends Action<ActionType> | |
? ActionsUnion | |
: never |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment