I would like to figure out if there is a way of applying a map
to a type predicate to be able to replace the repeated calls (one for each variable) in the following code snippet so that TSC (still) knows that A and B are iterables (which Sets are):
if(isSet(A) && isSet(B)) {
return isSuperSet( [...A], [...B])
}
isSet
is, of course, the type predicate:
function isSet(x:any): x is Set<unknown> { return x instanceof Set }
I tried replacing it with something that checks that [A,B]
is an array, Set<unknown>[]
, but that does not seem to work with this definition, as A
and B
loses their type inference and fall back to the "outer" looser definition.
function everyIsASet(array: any): array is Set<unknown>[] { return array.every(isSet);
I am a bit surprised, given that if [A,B]
is an array of Set
, that should imply that the individual elements would all be Set
s, and that the compiler cannot pick that up/loses this in the if block.
This related question seems to imply that this is possible, but I am not seeing what I am missing.
One way of "hacking" around this is to create temporary variables like this:
const arr = [A,B]
if(isSetArray(arr)) {
const [newA, newB] = arr;
return isSuperSet( [...newA], [...newB])
}
... which works, but seems unnecessary.