Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flowtype how to annotate union with optional fields

Tags:

flowtype

How to achieve the following in flow

export type Response = {
  err: string,
  data: ?Array<Object>,
} | {
  data: Array<Object>,
};

I want to express a type, which returns an error and optional data or no error field in case there none. But, which I use it as

return { err: 'todo' };
                ^^^^^^^^^^^^^^^ object literal. This type is incompatible with
.... Response
union: object type(s)
like image 257
bsr Avatar asked May 11 '16 14:05

bsr


1 Answers

In Flow, there is a difference between optional fields and nullable values.

  1. {key: ?valueType} means the object must contain key, and its value must be either null or of type valueType.

  2. {key?: valueType} means the object might contain key, and if key is present, its value must be of type valueType.

  3. {key?: ?valueType} means the object might contain key, and if key is present, its value must be either null or of type valueType.

Your use case needs either #2 or #3. Personally I would recommend not using #3 – I find that pattern more flexible than it needs to be.

like image 174
Nikita Avatar answered Oct 25 '22 04:10

Nikita