Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AppThunk pattern can't infer return type of thunk #17

Closed
ProdigySim opened this issue Mar 26, 2020 · 2 comments
Closed

AppThunk pattern can't infer return type of thunk #17

ProdigySim opened this issue Mar 26, 2020 · 2 comments

Comments

@ProdigySim
Copy link

Using the AppThunk type, I may write some thunk that returns a promise:

export const incrementAsync = (amount: number): AppThunk => async dispatch => {
  dispatch(incrementByAmount(amount))
  return await Promise.resolve(amount);
};

But, AppThunk does not seem to infer the return type here, and just uses void. So, incrementAsync gets a type of (amount: number) => AppThunk<void>.

Using a classic signature like

export const incrementAsync = (amount: number) => async (dispatch: Dispatch) => {
  dispatch(incrementByAmount(amount))
  return await Promise.resolve(amount);
};

gives us a type for incrementAsync of const incrementAsync: (amount: number) => (dispatch: Dispatch) => Promise<number> which infers the thunk return type properly.

Probably consider this more of a feature request, but it would be neat if there were a pattern that could support both the return type & parameter type inference here.

@markerikson
Copy link
Contributor

Yeah, it's a bit of a tradeoff. You should be able to do AppThunk<Promise<MyData>> for those cases where you need the promise result.

That said, this really isn't an issue that's specific to the template itself - it's more about documenting ways to use thunks with TS, which is better suited for the core Redux repo. If you can file a PR to update the core docs, I'd appreciate it. Thanks!

@ProdigySim
Copy link
Author

You could define another helper like

function createThunk<T>(thunk: AppThunk<T>) { return thunk; }

Which seems to convince Typescript to infer the return type properly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants