Home > Blockchain >  Cannot invoke an object which is possibly 'undefined' on onClick
Cannot invoke an object which is possibly 'undefined' on onClick

Time:11-09

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.

CodePudding user response:

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

  • Related