Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional function prop in React component Flow type check fail

I am using React's PropTypes and Flow type checker but I am having trouble getting an optional function prop to pass the type check. Here is an example:

var Example = React.createClass({
  propTypes: {
    exampleFn: React.PropTypes.func
  },

  handleClick: function() {
    if (this.props.exampleFn) {
      this.props.exampleFn();
    }
  },

  render: function() {
    return <a onClick={this.handleClick}>Click here</a>;
  }
});

Although I'm checking this.props.exampleFn is not null, running Flow's type checker against this code gives me the error

call of method exampleFn
Function cannot be called on possibly null or undefined value

I've tried different variations such as
if (this.props.exampleFn !== null && this.props.exampleFn !== undefined) {...}
or
this.props.exampleFn && this.props.exampleFn()
etc. to know that we're guarding against a possibly null/undefined value but I can't find anything that works. Of course, changing the prop type to React.PropTypes.func.isRequired results in no errors but I'd like to keep this prop optional.

How can I get an optional function prop to pass the type check?

like image 806
franky Avatar asked Dec 19 '14 06:12

franky


1 Answers

Here is one way we've found to keep the PropType optional but still have the Flow type check pass.

...

handleClick: function() {
  var exampleFn = this.props.exampleFn || null;
  if (exampleFn) {
    exampleFn();
  }
},

...
like image 182
franky Avatar answered Sep 18 '22 01:09

franky