Search code examples
reactjstypescriptreduxreact-reduxtsc

Get type definition for props.dispatch() for using TypeScript with React-Redux


I have this functional/stateless component:

import React from 'react';
import {useFormik} from 'formik';
import {connect} from "react-redux";

function mapStateToProps(){
  return {
     foo: "bar"
  }
}

interface OwnProps {
  propFromParent: number
}


type StateProps = ReturnType<typeof mapStateToProps>
type Props = StateProps & OwnProps


const SignupForm = (props: Props) => {


  const formik = useFormik({
    initialValues: {
      email: '',
      name: '',
      password: ''
    },
    onSubmit(values) {
      props.dispatch()   // props.dispatch is not defined!
    }
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="name">Full Name</label>
      <input
        id="name"
        name="name"
        type="name"
        onChange={formik.handleChange}
        value={formik.values.name}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default connect<StateProps, null, Props>(mapStateToProps)(SignupForm);

so I am getting this compile error:

enter image description here

So how can I include the type definition so that props.dispatch is defined? Just looking for help with the proper TS definitions.


Solution

  • You need to add a new function and pass it to connect() as second argument

    ...
    function mapDispatchToProps(dispatch): IDispatchProps {
     return {
      dispatch
     };
    }
    
    connect(mapStateToProps, mapDispatchToProps)