0

I'm working with a Typescript Angular2 site that uses RxJS Observables. I am taking a piece of user data and hitting two different API endpoints. I'm .forkJoining them together like so

var First: TypeA = this.api.FirstEndpoint(...);
var Second: TypeB = this.api.SecondEndpoint(...);
Observable.forkJoin(First, Second).subscribe((results: (TypeA|TypeB)[]) => {
    var first = <TypeA>results[0];
    var second = <TypeB>results[1];
    ...
});

While this technically works, I feel this is a bit clunky. Especially if I join more and more requests or a variable number of requests. Nothing says that results[0] is TypeA or that 1 is TypeB.

Is there a smoother way to type results or an alternative to forkJoin that will combine requests but keep their responses different (and thus typed more explicitly)?

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188

1 Answers1

0

You can define your own selector, which the compiler should use to infer the type of the resulting stream:

var combined = Observable.forkJoin(First, Second, (first, second) => {
  return { first, second };
});

combined.subscribe(result) => {
    // I don't think you'll need to explicitly cast
    var first = result.first;
    var second = result.second;
    ...
});
Calvin Belden
  • 3,114
  • 1
  • 19
  • 21