Skip to content

Instantly share code, notes, and snippets.

@nluo
Last active February 6, 2018 01:08
Show Gist options
  • Save nluo/dbf6badd65b19a9fb078d008b5024ef2 to your computer and use it in GitHub Desktop.
Save nluo/dbf6badd65b19a9fb078d008b5024ef2 to your computer and use it in GitHub Desktop.
React redux typings in typescript
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...
});
@nluo
Copy link
Author

nluo commented Feb 6, 2018

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

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