Description
The current Array#filter libdef defines the case of arr.filter(Boolean)
to return Array<$NonMaybeType<T>>
. Of course, filtering with Boolean
(or an identity function, for that matter) as the predicate filters out only truthy values.
The current definition is sufficient for using .filter(Boolean)
as an idiom for filtering out undefined/null, but it doesn't cover the reasonably common [..., (some condition) && value, ...].filter(Boolean)
case, where the condition is a boolean expression.
I think it'd be really neat if this example typechecked (contrived example):
const fn = (a: string, b: string): string[] => [a, b.length > 0 && b].filter(Boolean);
My line of thinking is that this could be solved with primitives $Truthy<T>
and $Falsy<T>
to restrict a type T to truthy (resp. falsy) values in T, if possible to represent in the type system. The libdef for Array#filter(Boolean)
would be changed to return Array<$Truthy<T>>
. I'm not sure what changes would be necessary to &&
and ||
to support this, but my line of thinking is that (x: a) && (y: b)
would be assigned type $Falsy<a> | b
. The flow implementation would have to hardcode a table such that $Truthy<boolean>
is true
, $Falsy<boolean>
is false
, $Falsy<number>
is 0 | NaN
, etc.
Ideally, then, [a, b.length > 0 && b]
would be typed as Array<string | $Falsy<boolean>>
<=> Array<string | false>
, and [a, b.length > 0 && b].filter(Boolean)
as Array<$Truthy<string | false>>
<=> Array<$Truthy<string> | $Truthy<false>>
<=> Array<$Truthy<string>>
<=> Array<string>
.
I'm assuming it wouldn't be possible to represent "non-empty string" or "non-zero-nor-NaN number" "natively" in the type system.