Created
March 8, 2018 17:53
-
-
Save Reshetnyak/80bfa9b7bf24710706f8f254b3864eb6 to your computer and use it in GitHub Desktop.
Action creator function
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
// needs to be feagure out creation of type Actions = increment | openModal.... | |
function actionCreator<T>(type: T): { type: T, new(): {type: T} } | |
function actionCreator<T, P>(type: T): { type: T, new(payload: P): {type: T, payload: P} } | |
function actionCreator<T, P>(type: T): { new(...args: any[]): {type: T, payload?: P} } { | |
return class { | |
static type: T = type; | |
type: T = type; | |
constructor(public payload?: P) { } | |
} | |
} | |
// action types | |
enum ActionTypes { | |
openModal = 'OPEN_MODAL', | |
increment = 'INCREMENT' | |
} | |
// action with payload | |
const increment = actionCreator<ActionTypes.increment, number>(ActionTypes.increment); | |
// action without payload | |
const openModal = actionCreator<ActionTypes.openModal>(ActionTypes.openModal); | |
// actions | |
// in reducers | |
function reducer(state: any, action: Actions) { | |
switch (action.type) { | |
case ActionTypes.increment: return state + action.payload | |
} | |
} | |
// const inc = actionCreator<'Hello'>('Hello'); | |
const inc = actionCreator<ActionTypes.hello>(ActionTypes.hello); | |
const r = new inc; | |
const t = inc.type; | |
const dec = actionCreator<ActionTypes.bye, number>(ActionTypes.bye); | |
const rr = new dec(10); | |
const tt = dec.type; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment