I’m going through Deborah Kurata’s Angular RXJS course and I’m getting a type error that I can’t pinpoint one of the types for and it’s throwing an error. Here is the action stream that uses scan() and is hollering:
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 is the error that it’s throwing:
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.
If I understand this right, it’s upset that the value in the scan() is typed as Product | Product[]. What I don’t understand is why it’s typed value this way. Since value is a variable, and we are declaring that ‘[] as Product[]’ toward the end of the tertiary, shouldn’t it override whatever the default variable tries to type?
Looking this error up on Google (even with keywords like, angular, rxjs, and scan()) it gives me scenarios that don’t look like anything like what we’re trying to do with an array. If someone has a resource, I’m happy to learn from it. It’s possible that I’ve just not sorted through a long enough search. As far as I can tell it’s a type error and it seems obscure. I appreciate any help that you might have!