Ryan Wheale
Ryan Wheale

Reputation: 28390

FlowJS - does not recognize when there is a value on an optional field

I have the following type definition (note that path is optional):

type MyType = {
  name: string,
  path?: Array<string>
};

Then in my code I have certain places where path definitely has a value:

const meta: MyType = {
  name: 'Foo',
  path: []
}

meta.path.unshift('bar');

In the above example meta.path has a value, but flow complains that it cannot call "unshift" on undefined. I get that undefined is a valid value for path, but in this case path definitely has a value 100% percent of the time. The only way to fix it is to this completely unnecessary code:

(meta.path || []).unshift(...);

Upvotes: 0

Views: 87

Answers (1)

foxes
foxes

Reputation: 856

All Flow knows is that const meta is of type MyType, and that MyType has path which is optional. It doesn't know whether path exists or not, and so it correctly throws that error.

If you want path, you need to wrap it in some sort of if check or something similar to what you have done.

Upvotes: 1

Related Questions