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 || []);
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.
Most helpful comment
You can make
emptyArraywork for both functions by either annotating it:Or by annotating
BarandBazas read-only arrays: