简体   繁体   中英

TypeScript: Cannot invoke an object which is possibly 'undefined'

I've a reusable component that accepts an optional onClick callback function as a prop.

I've defined the Props interface as folllows:

interface Props {
  prop1: string;
  prop2: string;
  optionalClickFn?: () => void;
}

The functional React (JSX) component as follows:

const ExampleComponent = (props: Props) => {
    return{
        { props.optionalClickFn ? <div
          className="delete-btn"
          onClick={() => props.optionalClickFn()}
        >
          <FontAwesomeIcon icon={faTimesCircle} color="red" />
        </div> : <div></div>}
         }
}

I've defined an optional prop 'optionalClickFn', therefore I am first checking if it exist before executing the function. However, i still get the error: Cannot invoke an object which is possibly 'undefined'.

I found the solution. Making the check that way was not working. If I put another if condition inside the onClick prop, it works as expected.

  {props.optionalClickFn ? (
    <div
      className="delete-btn"
      onClick={() => {
        if (props.optionalClickFn) {
          return props.optionalClickFn();
        }
      }}
    >
      <FontAwesomeIcon icon={faTimesCircle} color="red" />
    </div>
  ) : <div></div>}

I'm still unsure why it doesn't work the way I wrote in the original question though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM