Last active
June 22, 2018 17:00
-
-
Save deptno/a6741cb852da16a2df23cb2200ffc10a to your computer and use it in GitHub Desktop.
strong typed redux thunk action with typescript@2.8
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 {ThunkAction} from 'redux-thunk' | |
export const thunks: ThunkActionCreators = { | |
thunkA: () => { | |
return (dispatch, getState, extraArgs) => { | |
setTimeout(function useTimeoutBecauseImThunk() { | |
dispatch(actions.actionA()) | |
}, 1000) | |
} | |
}, | |
thunkB: () => { | |
return (dispatch, getState, extraArgs) => { | |
setTimeout(function useTimeoutBecauseImThunk() { | |
const state = getState() | |
state.a | |
state.b | |
// state.c // error | |
dispatch(actions.actionA()) | |
}, 1000) | |
} | |
} | |
} | |
interface ThunkActionCreators { | |
[key: string]: ThunkActionCreator | |
} | |
interface ThunkActionCreator { | |
(...args: any[]): ThunkAction<void, State, {}> | |
} | |
function createAction<A extends ActionTypes>(type: A): TypedAction<A> | |
function createAction<A extends ActionTypes, P>(type: A, payload: P): TypePayloadAction<A, P> | |
function createAction(type, payload?) { | |
return payload !== undefined ? {type, payload} : {type} | |
} | |
enum ActionTypes { | |
ACTION_1 = 'action 1', | |
ACTION_2 = 'action 2' | |
} | |
export const actions = { | |
actionA: () => createAction(ActionTypes.ACTION_1, {a:1}), | |
actionB: () => createAction(ActionTypes.ACTION_2, {b:1}), | |
} | |
interface TypedAction<A> { | |
type: A | |
} | |
interface TypePayloadAction<A, P> extends TypedAction<A> { | |
payload: P | |
} | |
function reducer(state: State, action: ReturnType<typeof actions[keyof typeof actions]>): State { | |
switch (action.type) { | |
case ActionTypes.ACTION_1: | |
action.payload.a | |
// action.payload.b // error | |
return { | |
...state, | |
a: action.payload.a | |
} | |
case ActionTypes.ACTION_2: | |
// action.payload.a // error | |
action.payload.b | |
return { | |
...state, | |
b: action.payload.b | |
} | |
} | |
} | |
export interface State { | |
a: number | |
b: number | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Forgive me if i'm wrong, but are thunks never used in this setup? Can you show an example of how you call those methods?