Reputation: 1333
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?
Upvotes: 6
Views: 11713
Reputation: 1333
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();
}
},
...
Upvotes: 10