Created
December 26, 2020 18:02
-
-
Save KonradSzwarc/c256f4e472508dea13fbeb8f69f5b3aa to your computer and use it in GitHub Desktop.
Function that generates redux action creator
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 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