Skip to content

Instantly share code, notes, and snippets.

@JakeSidSmith
Last active October 12, 2018 14:29
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 JakeSidSmith/8bdb9c7a7d113ba734e35104a2238fc0 to your computer and use it in GitHub Desktop.
Save JakeSidSmith/8bdb9c7a7d113ba734e35104a2238fc0 to your computer and use it in GitHub Desktop.
wrapThunkAction - correctly types thunk actions as if they had been mapped with dispatch
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { wrapThunkAction } from './somewhere';
import { action } from './actions';
const wrappedAction = wrapThunkAction(action);
interface DispatchProps {
action: typeof wrappedAction;
}
type Props = DispatchProps;
class MyComponent extends Component<Props> {
public render () {
return <p onClick={this.onClick}>Hello, World!</p>;
}
private onClick = () => {
// Due to the wrapped types we can now chain off this action (if it returned a promise)
this.props.action()
.then((response) => {
console.log(response);
})
}
}
export default connect(undefined, { action: wrappedAction })(MyComponent)
import { Action } from 'redux';
import { ThunkDispatch } from 'redux-thunk';
export type ThunkActionCreator<S, R, A = any, B = any, C = any> = (a: A, b: B, c: C) => (dispatch: ThunkDispatch<S, any, Action>, getState: () => S, extra: any) => R;
export type AnyThunkActionCreator<S, R> = (...args: any[]) => (dispatch: ThunkDispatch<S, any, Action>, getState: () => S, extra: any) => R;
export function wrapThunkAction<S, R>(action: ThunkActionCreator<S, R>): () => R;
export function wrapThunkAction<S, R, A>(action: ThunkActionCreator<S, R, A>): (a: A) => R;
export function wrapThunkAction<S, R, A, B>(action: ThunkActionCreator<S, R, A, B>): (a: A, b: B) => R;
export function wrapThunkAction<S, R, A, B, C>(action: ThunkActionCreator<S, R, A, B, C>): (a: A, b: B, c: C) => R;
export function wrapThunkAction<S, R>(action: AnyThunkActionCreator<S, R>): (...args: any[]) => R {
return action as any;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment