Why can't I use spread operator with Typescript and RXJS pipe?

Viewed 556

Given code like this:

const pipeMethods: OperatorFunction<any, any>[] = [];

return of(req).pipe(...pipeMethods);

I get an error that says A spread argument must either have a tuple type or be passed to a rest parameter

Doing return of(req).pipe.apply(null, pipeMethods); instead gets me

Argument of type 'OperatorFunction<any, any>[]' is not assignable to parameter of type '[op1: OperatorFunction<AjaxConfig, unknown>, op2: OperatorFunction<unknown, unknown>, op3: OperatorFunction<unknown, unknown>, op4: OperatorFunction<unknown, unknown>, op5: ... 5 more ..., op6: OperatorFunction<...>]'.

When using a ts-ignore all my code functions fine. I'm having trouble understanding the error here.

1 Answers

I remember seening people having problems with using the spread operator inside pipe() but I can't find anywhere what the problem was. Check out this GitHub issue https://github.com/ReactiveX/rxjs/issues/3989 for some addtional info.

Anyway, I think at this moment the best way is using pipe function that comes from rxjs package (I'm not talking about Observable.pipe() now):

import { pipe as pipeFromArray, of } from 'rxjs';

...

const operators = [
  map(...),
  filter(...),
  tap(...),
];

const source = of('World').pipe(pipeFromArray(...operators));

Live demo: https://stackblitz.com/edit/rxjs-ggiquc

Related