flow icon indicating copy to clipboard operation
flow copied to clipboard

Strange behaviour when variable is inited with null

Open lyosha-v opened this issue 9 years ago • 3 comments

Hi!

I've got a test, that looks like this

declare function it(name: string, fn: any): void;
declare function describe(fn: any): void;
declare function beforeEach(fn: any): void;

declare function f(): {prop: string};

describe(() => {
  let result = null;
  
  beforeEach(() => {
    result = f();
  });
  
  it('some test', () => {
    result.prop;
  });
});

I've got some function f() that always returns some value that is not a null, but I init result variable with null value. Flow shows me an error on this test:

15:     result.prop;
               ^ property `prop`. Property cannot be accessed on possibly null value
15:     result.prop;
        ^ null

The error disappears if I change let result = null; to let result;. (Here is an example in Flow REPL)

Is it an expected behaviour or a bug?

lyosha-v avatar Apr 24 '17 13:04 lyosha-v

This is expected. Flow has no way of knowing that beforeEach callback is going to be executed before it callback, so result has type null | {prop: string}

vkurchatkin avatar Apr 24 '17 14:04 vkurchatkin

Why does removing = null makes Flow to behave in other way? Isn't it equal undefined | {prop: string}?

lyosha-v avatar Apr 25 '17 09:04 lyosha-v

@verkholantsev this is either a bug or (most likely) an unsafe feature to support behavior that you want

vkurchatkin avatar Apr 25 '17 12:04 vkurchatkin