I'm currently working through an Angular RXJS course by Deborah Kurata and I've encountered a type error that I can't seem to figure out. The error is being thrown from the action stream which uses scan(). Here's the code snippet:
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[])
)
Here's the specific error message:
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.
From my understanding, the issue arises from the value in the scan() method being typed as Product | Product[]. I am puzzled why it's being inferred this way since we explicitly declare '[] as Product[]' at the end. Shouldn't this override any default typing for the variable?
When researching this error online, I couldn't find relevant examples related to arrays within Angular and RXJS. If anyone has a useful resource or insight on how to resolve this type error, I would greatly appreciate your help! It seems like a complex issue to pinpoint and understand fully.