Flow: Flow incorrectly reports type incompatibility after undefined check when using Array.map

Created on 8 Dec 2016  路  1Comment  路  Source: facebook/flow

This code:

// @flow
function func1(a?: string[], b?: string ) {

    if (a === undefined || b === undefined) {
        return;
    }
    a.map(item => func2(item, b));
}

function func2(a: string, b: string ) {
    console.log(a);
    console.log(b);
}

console.log(func1(['a'], 'b' ));

Produces these errors:

test.js:7
  7:     a.map(item => func2(item, b));
                                   ^ undefined. This type is incompatible with the expected param type of
 10: function func2(a: string, b: string ) {
                                  ^^^^^^ string

If you strip the type annotations and run it the code runs fine console logging 'a' and 'b' as expected.

Without the

a.map(item => func2(item, b)); part Flow is also fine with it

// @flow
function func1(a?: string[], b?: string ) {
    if (a === undefined || b === undefined) {
        return;
    }
    func2(a[0], b);
}

function func2(a: string, b: string ) {
    console.log(a);
    console.log(b);
}

console.log(func1(['a'], 'b' ));

Most helpful comment

This is normal, flow is pessimistic about refinements, it considers that func2 could modify b.

See #2895 for instance. As for a fix, you can redeclare b as a constant

You can also do as said by gcanti https://github.com/facebook/flow/issues/2877#issuecomment-262390960

Another way to fix the error is to set the experimental.const_params=true option in the [options] section of .flowconfig

>All comments

This is normal, flow is pessimistic about refinements, it considers that func2 could modify b.

See #2895 for instance. As for a fix, you can redeclare b as a constant

You can also do as said by gcanti https://github.com/facebook/flow/issues/2877#issuecomment-262390960

Another way to fix the error is to set the experimental.const_params=true option in the [options] section of .flowconfig

Was this page helpful?
0 / 5 - 0 ratings