Search code examples
typescriptreact-reduxreact-tsx

Property 'handleLoginDisplay' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>


I have the following code in Typescript. Why does the compiler throws an error?

import { connect } from 'react-redux';
import React from "react";
import { Link, Redirect } from "react-router-dom";

class HeaderComponent extends React.Component {
    render() {
        return (
            <header>
                <div><Link to="">Sign up</Link></div>
                <div>{this.props.handleLoginDisplay}</div>
            </header>
        )
    }
}

const mapStateToProps = (state: { showLoginModal: any; }) => {
    return {
        showLoginModal: state.showLoginModal
    }
}

const mapDispatchToProps = (dispatch: (arg0: { type: string; }) => void) => {
    return {
        handleLoginDisplay: () => dispatch({ type: 'HANDLE_LOGIN_DISPLAY' })
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(HeaderComponent);

Property 'handleLoginDisplay' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.ts(2339)


Solution

  • Because you need to tell ts what kind of props the component will receive with an interface like this:

    interface Props {
        showLoginModal: boolean;
        handleLoginDisplay: () => void;
    }
    
    class HeaderComponent extends React.Component<Props> {
        render() {
            return (
                <header>
                     <div><Link to="">Sign up</Link></div>
                     <div>{this.props.handleLoginDisplay}</div>
                 </header>
         )}
     }
    

    This will let ts know that HeaderComponent accepts these props. You should also remove the any from mapStateToProps.