Flow: Array type with default empty array from a variable

Created on 21 Nov 2017  路  2Comments  路  Source: facebook/flow

FlowTry

type Bar = Array<string>;
type Baz = Array<number>;

const someNull = null;
const emptyArray = [];

function heh(bar: ?Bar) {
  return null;
}

function hah(baz: ?Baz) {
  return null;
}

heh(someNull || emptyArray);
hah(someNull || emptyArray);

Resulting in:

16: hah(someNull || emptyArray);
        ^ empty array literal. This type is incompatible with the expected param type of
11: function hah(baz: Baz) {
                      ^ array type
Type argument `T` is incompatible:
1: type Bar = Array<string>;
                    ^ string. This type is incompatible with
2: type Baz = Array<number>;
                    ^ number
16: hah(someNull || emptyArray);
        ^ empty array literal. This type is incompatible with the expected param type of
11: function hah(baz: Baz) {
                      ^ array type
Type argument `T` is incompatible:
2: type Baz = Array<number>;
                    ^ number. This type is incompatible with
1: type Bar = Array<string>;
                    ^ string

This one works though:

type Bar = Array<string>;
type Baz = Array<number>;

const someNull = null;

function heh(bar: Bar) {
  return null;
}

function hah(baz: Baz) {
  return null;
}

heh(someNull || []);
hah(someNull || []);

Most helpful comment

You can make emptyArray work for both functions by either annotating it:

const emptyArray: Array<any> = [];

Or by annotating Bar and Baz as read-only arrays:

type Bar = $ReadOnlyArray<string>;
type Baz = $ReadOnlyArray<number>;

All 2 comments

You can make emptyArray work for both functions by either annotating it:

const emptyArray: Array<any> = [];

Or by annotating Bar and Baz as read-only arrays:

type Bar = $ReadOnlyArray<string>;
type Baz = $ReadOnlyArray<number>;

Ah, never seen $ReadOnlyArray before.
And that's Array<any> is pretty neat too.
Thanks!
I guess I could close this.

Was this page helpful?
0 / 5 - 0 ratings