I'm experiencing a TypeScript type check failure when using the forkJoin operator form RxJS. This is the code in question:
let products = this.http.get(productUrl, { headers: this.headers })
.map(response => response.json().data as Product[]);
let loans = Observable.of(loan);
return Observable.forkJoin([products, loans])
.map(data => {
let resultProducts = data[0] as Product[];
if (resultProducts.length > 0) {
lead.Product = resultProducts.find(i => i.ID == productId);
}
lead.Loan = data[1];
return lead;
});
The error tsc is emitting is:
Type 'Loan' cannot be converted to type 'Product[]'.
My understanding of forkJoin is that data[0] should be a Product[] and data[1] should be a Loan, but tsc seems to disagree. Is my understanding incorrect? Am I missing some typing that would tell tsc hat I want?
There are numerous signature overloads for
forkJoin
.When you call
forkJoin
, passing an array:The signature that's matched is this one:
Note that there is only a single type variable (
T
), so all of the array elements are inferred to be a single type. AndT
will beProduct[] | Loan
, which is why the error you mentioned is effected. (You cannot assert that something that could potentially be aLoan
is aProduct[]
.)If you specify separate arguments instead:
It will match this signature:
And the emitted value will have a tuple type
[Product[], Loan]
and the error won't be effected, as TypeScript will know thatdata[0]
is aProduct[]
.Try using Observable.forkJoin without passing in an array.