Skip to content

Instantly share code, notes, and snippets.

@KonradSzwarc
Created December 26, 2020 18:02
Show Gist options
  • Save KonradSzwarc/c256f4e472508dea13fbeb8f69f5b3aa to your computer and use it in GitHub Desktop.
Save KonradSzwarc/c256f4e472508dea13fbeb8f69f5b3aa to your computer and use it in GitHub Desktop.
Function that generates redux action creator
type ResolveType<T> = T extends (...args: any[]) => Record<string, unknown>
? T
: { [K in keyof T]: T[K] };
export function createAction<
Type extends string,
Args extends any[] = [],
Return extends Record<string, unknown> = Record<string, unknown>
>(
type: Type,
createHandler?: (...args: Args) => Return,
): (...args: Args) => ResolveType<{ type: Type } & Return> & { type: Type } {
const actionCreator = (...args: Args): ResolveType<{ type: Type } & Return> & { type: Type } => {
const customProps = createHandler != null ? createHandler(...args) : {};
return { type, ...customProps } as ResolveType<{ type: Type } & Return>;
};
return Object.assign(actionCreator, { type });
}
export default createAction;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment