Skip to content

Instantly share code, notes, and snippets.

@deptno
Last active June 22, 2018 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deptno/a6741cb852da16a2df23cb2200ffc10a to your computer and use it in GitHub Desktop.
Save deptno/a6741cb852da16a2df23cb2200ffc10a to your computer and use it in GitHub Desktop.
strong typed redux thunk action with typescript@2.8
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
}
@dcbartlett
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment