首页 > 解决方案 > 如何使用扫描运算符来计算 void observable 的发射值?

问题描述

我需要一个 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

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

   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'.

也许我只是累了,但我似乎无法修复错误。我看不出我的scan()接线员有什么问题。

标签: angulartypescriptrxjsobservable

解决方案


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

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

需要注意的scan类型。reduce基本上,它们就是这样,因为它们需要像旧版本的 TypeScript 那样。现在 TypeScript 2.8 是 RxJS 6 的最低支持版本,应该可以改进类型。


推荐阅读