简体   繁体   中英

TypeScript return type of Redux action

I have this in a codebase;

export const login = (user, pass) => {
  return (dispatch) =>    dispatch({ type: LOGIN });
}

what is the return type of login ?

I tried this:

export const login = (user, pass)  : ReducerAction {
  return (dispatch) =>  dispatch({ type: LOGIN });
}

and that type is definitely wrong. What is the correct TS return type here? Retarded difficult to find an answer to this online.

It will be sufficient to provide an interface for your redux action dispatch props in the following manner:

interface DispatchProps {
  login: () => void;
}

And then you can use the above interface to provided the typings for your mapDispatchToProps .

const mapDispatchToProps = (dispatch: Dispatch<DispatchProps>) =>
  bindActionCreators({
    login: () => login(),
  }, dispatch);

If you are working with react/redux/TypeScript, I would recommend this guide , as it has tons of resources. In addition, you might want to install typesafe-actions , which is a form of "Typesafe utilities for "action-creators" in Redux / Flux Architecture".

The problem here is that Typescript does not know the type of dispatch . It could be anything, as far as Typescript knows it is just some random function argument and could have any type. You need to declare it as the correct type and Typescript will be able to infer the rest:

const LOGIN = "LOGIN";

type LoginAction = {
  type: typeof LOGIN
}

const login = (user, pass) => (dispatch: React.Dispatch<LoginAction>) => dispatch({type: 'LOGIN'});

Note that the login action needs to have a declared type as well, because that is passed to the generic React.Dispatch type so that Typescript knows that kind of type it is dispatching.

You might need to install the @types/react-redux package to get the React.Dispatch type, I'm not sure where it comes from off the top of my head.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM