Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot invoke an object which is possibly 'undefined' on onClick

interface Alertprops {
    showAlert?: showAlertType,
    HideAlert?: () => void,
    onClick?: () => void,

}

interface Alertstate {
    alertMess?: string,
    showAlert?: boolean,
    alertType?: string,
    showReload?: boolean,
    

}

class Alert extends Component<Alertprops,Alertstate> {
    constructor(props:Alertprops) {
        super(props)

        this.state = {
            alertMess:'',
        }
    }

alertBox() {
        return (
            <div className="inner-box">
                {this.state.alertMess}
                <br/>
                {this.state.showReload ? (<a className="reload-link" onClick={()=>{window.location.reload()}}>Reload page</a>):(null)}
                <a onClick={()=>{this.props.HideAlert()}} className="close-alert">X</a>
            </div>
        )
    }

on onClick={()=>{this.props.HideAlert()}} I get error "Cannot invoke an object which is possibly ‘undefined’" what Im doing wrong? just started use TS.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

hi if you pass function as props that can be undefined you can pass it like this

this.props.HideAlert?.()

this can just run only if you get it as props

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading