Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Last active July 8, 2021 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fostyfost/21e142d5e58da86bcb2b690588ae5d3b to your computer and use it in GitHub Desktop.
Save fostyfost/21e142d5e58da86bcb2b690588ae5d3b to your computer and use it in GitHub Desktop.
Redux Action Helper
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>
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