1

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)

John Cane
  • 13
  • 2
  • Does this answer your question? [Property 'value' does not exist on type 'Readonly<{}>'](https://stackoverflow.com/questions/47561848/property-value-does-not-exist-on-type-readonly) – Michael Freidgeim Oct 01 '20 at 08:34

1 Answers1

1

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.

Domino987
  • 8,475
  • 2
  • 15
  • 38