flow icon indicating copy to clipboard operation
flow copied to clipboard

Null check throws error when checked in an outer function

Open Xesued opened this issue 10 years ago • 2 comments

With this:

/* @flow */
type ItemMap = {
    [id: number]: string;
}

type ItemAction = {
    type: string;
    items?: ItemMap;
}

function getFirstActionItem (action: ItemAction) {
    if(action.items == null) {
        return;
    }

    const fun = (itemId: number) => {
        return action.items[itemId];
    };

    return fun(0);
}

I get errors:

src/index.js:17
 17:        return action.items[itemId];
                   ^^^^^^^^^^^^^^^^^^^^ access of computed property/element. Computed property/element cannot be accessed on possibly undefined value
 17:        return action.items[itemId];
                   ^^^^^^^^^^^^ undefined


Found 1 error

Expect no errors since I did the null check on line 12.

Xesued avatar Mar 24 '16 19:03 Xesued

This is expected behavior. See the documentation here: http://flowtype.org/docs/dynamic-type-tests.html#caveats

samwgoldman avatar Mar 24 '16 21:03 samwgoldman

That is a "caveat" :) Sorry for the noise.

Xesued avatar Mar 24 '16 22:03 Xesued