Last active
February 6, 2018 01:08
-
-
Save nluo/dbf6badd65b19a9fb078d008b5024ef2 to your computer and use it in GitHub Desktop.
React redux typings in typescript
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 { Dispatch } from 'redux'; | |
import { ThunkAction } from 'redux-thunk'; | |
import { getStore, IState } from './my_store'; | |
let store = getStore(); | |
// Create myThunkAction function with a type of ThunkAction<R, S, E> | |
let myThunkAction: ThunkAction<Promise<string>, IState, null> = | |
(dispatch: Dispatch<IState>, getState: () => IState) => { | |
return new Promise<string>((resolve, reject) => { | |
// do async stuff with getState() and dispatch(), then... | |
resolve('done!'); | |
}); | |
} | |
store.dispatch(myThunkAction) | |
.then(() => { | |
// do stuff after the thunk has finished... | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basically the trick is to define your thunk function as a ThunkAction.
The ThunkAction<R, S, E> type is a generic type that takes 3 properties:
R - thunk function return type - it is a good idea to return a Promise from your thunk function so you can await the result if needed
S - State type - an interface that represents your redux store shape
E - extraArgument type - see https://twitter.com/dan_abramov/status/730053481919303685?lang=en
Taking notes from reduxjs/redux-thunk#103