如何使用扫描运算符来计算 void observable 的发射值?

Rea*_*lar 2 observable rxjs typescript angular

我需要一个 void 类型的可观察对象,它发出发出的 void 值的数量。

const subject = new Subject<void>();

subject.pipe(
    scan((acc, curr) => acc + 1, 0)
).subscribe(count => console.log(count));

subject.next(); // should output 1
subject.next(); // should output 2
subject.next(); // should output 3
Run Code Online (Sandbox Code Playgroud)

上面给出了以下编译器错误:

   TS2345: Argument of type 'MonoTypeOperatorFunction<number>' is not 
      assignable to parameter of type 'OperatorFunction<void, number>'.
      Types of parameters 'source' and 'source' are incompatible.
      Type 'Observable<void>' is not assignable to type 'Observable<number>'.
      Type 'void' is not assignable to type 'number'.
Run Code Online (Sandbox Code Playgroud)

也许我只是累了,但我似乎无法修复错误。我没发现我的scan()操作员有什么问题。

car*_*ant 5

要解决您的问题,您可以为传递给 的函数的参数指定类型scan,如下所示:

subject.pipe(
  scan((acc: number, curr: void) => acc + 1, 0)
).subscribe(count => console.log(count));
Run Code Online (Sandbox Code Playgroud)

scan和 的打字reduce需要一些注意。基本上,它们之所以如此,是因为它们需要像旧版本的 TypeScript 那样。现在 TypeScript 2.8 是 RxJS 6 支持的最低版本,应该可以改进打字。