Home > other >  Struggling with the rxjs `merge` interface
Struggling with the rxjs `merge` interface

Time:09-29

I have an issue with the RxJs merge interface:

export function merge<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;

So, based on this I created the following

const a$ = of('a').pipe(delay(1000));
const b$ = of('b');
const c$ = of('c').pipe(delay(10));

const y = merge<string[]>(d$, e$, f$) as Observable<string[number]>;

Nothing is complaining here. But when I use a little bit more complex interface

interface Foo<A = unknown, B = { id: string}> {
    input: A;
    output?: B;
} 

const a$ = of({input: 'a'}).pipe(delay(1000));
const b$ = of({input: 'b'});
const c$ = of({input: 'c'}).pipe(delay(10));

const x = merge<Foo<string>[]>(a$, b$, c$) as Observable<Foo<string>[number]>;

It complains about number

Type 'Foo<string, { id: string; }>' has no matching index signature for type 'number'. enter image description here

I must do something wrong here, any suggestions what my mistake is?

CodePudding user response:

The merge will combine all observable into one, so the return type a union of all types.

In your first case : Observable<string>

and your second one : Observable<{input: string}>

And no need to specify the generic, the compiler can infer the type itself.


Lets decompose the type :

export function merge<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;

A is generic with a constraint of Array<unknown>.

Knowing A, A[number] means every type of the array type A.

This means with Foo = [string, number];, Foo[number] equals string | number.

  • Related