Last active
October 12, 2018 14:29
-
-
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
This file contains hidden or 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 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) |
This file contains hidden or 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 { 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