materialdreams materialdreams - 1 year ago 96
Javascript Question

How to specify a parameter that can be undefined in flowjs

I'm new to flowjs and do not yet understand how the typical use case of an undefined parameter should be modeled in flowjs.

function msg(message: string, callback: ?Function) {
// ...
if (_.isFunction(callback)) {

When checking the above function with flow, the following error message is shown:

  • Function cannot be called on possibly null value function call.

  • Function cannot be called on possibly undefined value

I do understand why the errors are shown but I'm not sure how to tell flowjs that this is intentional because the callback is only invoked when the parameter is not null or undefined?

Answer Source

Flow does not know that _.isFunction(callback) returns true only if callback is a function. All it knows is that it returns a boolean (if you have the interface file for underscore/lodash set up). You should do native JS checks instead, then Flow can refine the type of callback from ?Function to Function. Like this: if (typeof callback === 'function') { callback() }.

A simpler type check should work as well: if (callback) { callback() } because Flow knows that if callback is not falsey, it has to be a function.

See more at

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download