错误 TS2769:没有重载与使用来自 RXJS Angular 17 的 scan() 的此调用相匹配

问题描述 投票:0回答:1

我正在学习 Deborah Kurata 的 Angular RXJS 课程,我遇到了一个类型错误,我无法确定其中一种类型,并且它抛出了一个错误。这是使用 scan() 并大声喊叫的操作流:

private productAddedSubject = new Subject<Product>();
productAddedAction$ = this.productAddedSubject.asObservable();

productsToAdd$ = merge(
  this.productsWithCategory$,
  this.productAddedAction$
).pipe(
    scan((acc, value) =>
      (value instanceof Array) ? [...value] : [acc, value], [] as Product[])
  )

这是它抛出的错误:


Error: src/app/products/product.service.ts:69:7 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(accumulator: (acc: Product[], value: Product | Product[], index: number) => Product[], seed: Product[]): OperatorFunction<Product | Product[], Product[]>', gave the following error.
    Type '(Product | Product[])[]' is not assignable to type 'Product[]'.
      Type 'Product | Product[]' is not assignable to type 'Product'.
        Type 'Product[]' is missing the following properties from type 'Product': id, productName
  Overload 2 of 3, '(accumulator: (acc: Product[] | (Product | Product[])[], value: Product | Product[], index: number) => (Product | Product[])[], seed: Product[]): OperatorFunction<...>', gave the following error.
    Argument of type '(acc: Product[], value: Product | Product[]) => (Product | Product[])[]' is not assignable to parameter of type '(acc: Product[] | (Product | Product[])[], value: Product | Product[], index: number) => (Product | Product[])[]'.
      Types of parameters 'acc' and 'acc' are incompatible.
        Type 'Product[] | (Product | Product[])[]' is not assignable to type 'Product[]'.
          Type '(Product | Product[])[]' is not assignable to type 'Product[]'.

69       scan((acc, value) =>
         ~~~~

  node_modules/rxjs/dist/types/internal/operators/scan.d.ts:3:49
    3 export declare function scan<V, A>(accumulator: (acc: A, value: V, index: number) => A, seed: A): OperatorFunction<V, A>;
                                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The expected type comes from the return type of this signature.

如果我理解正确的话,那么 scan() 中的值被输入为 Product | 会令人沮丧。产品[]。我不明白的是为什么它以这种方式输入值。由于 value 是一个变量,并且我们在第三级末尾声明“[] as Product[]”,因此它不应该覆盖默认变量尝试输入的任何内容吗?

在 Google 上查找此错误(即使使用 Angular、rxjs 和 scan() 等关键字),它给我的场景看起来与我们尝试对数组执行的操作完全不同。如果有人有资源,我很乐意从中学习。可能是我没有对足够长的搜索进行排序。据我所知,这是一个类型错误,而且看起来很晦涩。我感谢您可能提供的任何帮助!

angular typescript rxjs
1个回答
0
投票

您的 acc 是一个数组,因此当您将其与新值组合时,请记住使用扩展运算符“...acc”,如下所示:

productsToAdd$ = merge(
  this.productsWithCategory$,
  this.productAddedAction$
).pipe(
    scan((acc, value) =>
      (value instanceof Array) ? [...value] : [...acc, value], [] as Product[])
  )
© www.soinside.com 2019 - 2024. All rights reserved.