Flow doesn't recognise refinement inside callback

前端 未结 1 1086
日久生厌
日久生厌 2021-01-19 10:03

This code passes the flow check:

/* @flow */

function test (list: ?Array): Promise {
  if(list !== null && list !== unde         


        
相关标签:
1条回答
  • 2021-01-19 10:18

    Basically, Flow doesn't know that your type refinement (null check) will hold at the time when () => list.length is executed. Inside that callback Flow only looks at the type of list – which says it can be null.

    The difference between first and second snippet is that in the second snippet list is crossing a function boundary – you're using it in a different function than where you refined its type.

    One solution is to extract list.length into a variable, and use that variable in the callback.

    var length = list.length;
    return Promise.resolve().then(() => length)
    

    This might also work:

    var list2: Array<string> = list;
    return Promise.resolve().then(() => list2.length)
    

    Note that this problem exists even for immediately invoked callbacks, e.g. when using map or forEach. There is an issue on flow's github about this, but I couldn't find it after a quick search.

    0 讨论(0)
提交回复
热议问题