Last active
June 13, 2019 16:22
-
-
Save captain-yossarian/c5631d1fc7d847fa7116d16e7ab4f113 to your computer and use it in GitHub Desktop.
TS Redux action factory
This file contains 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 { Action } from 'redux'; | |
export enum Constants { | |
ACTION_NAMESPACE = 'ACTION_NAMESPACE', | |
} | |
export type ActionPayload<T, P> = Action<T> & { payload: P }; | |
interface IPayload{ | |
id: string; | |
mode: Modes; | |
} | |
type AllValues<T> = { [P in keyof T]: P extends Constants ? T[P] : null }[keyof T]; | |
export interface IActionMap { | |
[Constants.ACTION_NAMESPACE]: IPayload; | |
} | |
export type AllActionsPayload = AllValues<IActionMap>; | |
type TypeTest<T> = keyof T extends Constants ? true : false; | |
/** | |
* @test | |
* if `unitTest` will be highlighted by red color, @interface IActionMap is not correct | |
*/ | |
const unitTest: TypeTest<IActionMap> = true; | |
export const createAction = <T extends keyof IActionMap>(type: T) => ( | |
payload: IActionMap[T] | |
): Action<T> & { payload: IActionMap[T] } => ({ | |
type, | |
payload, | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment