I am using redux and redux-thunk with typescript. I am trying to inject to a component through connect() a simple thunk action creator, using mapDispatchToProps.
Actions
export enum TestActionTypes {
THUNK_ACTION = "THUNK_ACTION"
}
export interface ThunkAction {
type: TestActionTypes.THUNK_ACTION;
}
export type TestAction = ThunkAction;
Action Creators
export function thunkActionCreator() {
return function(dispatch: Dispatch<any>) {
dispatch({ type: TestAction.THUNK_ACTION });
};
Connected Component
interface DemoScreenState {}
interface OwnProps {}
interface StateProps {}
interface DispatchProps {
testThunk: () => void;
}
type DemoScreenProps = StateProps & DispatchProps & OwnProps;
class DemoScreen extends React.Component<
DemoScreenProps,
DemoScreenState
> {
constructor(props: DemoScreenProps) {
super(props);
}
componentDidMount() {
this.props.testThunk();
}
render() {
return null;
}
}
function mapStateToProps(state: any): StateProps {
return {};
}
function mapDispatchToProps(dispatch: Dispatch<any>): DispatchProps {
return {
testThunk: () => dispatch(thunkActionCreator())
};
}
export default connect<StateProps, DispatchProps, OwnProps>(
mapStateToProps,
mapDispatchToProps
)(DemoScreen);
Store
import { createStore, applyMiddleware } from "redux";
import rootReducer from "./RootReducer";
import thunk from "redux-thunk";
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
However, I am encountering two issue when using connect(). First of all, I get a type error for the declaration of testThunk in mapDispatchToProps.
Argument of type '(dispatch: Dispatch) => void' is not assignable to parameter of type 'Action'. Property 'type' is missing in type '(dispatch: Dispatch) => void'. I don't know how to handle this, as by definition a thunk is different from a plain action.
* EDIT 24/10/2018 * cf answer below, using:
"@types/react-redux": "^6.0.9",
"react": "16.3.1",
"react-native": "~0.55.2",
"react-redux": "^5.0.7",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0"