Search code examples
angulartypescriptstringobservableangular13

Argument of type '(string | undefined)[]' is not assignable to parameter of type 'string[]'


I have some code but get error with angular 13 string[]

Argument of type '(string | undefined)[]' is not assignable to parameter of type 'string[]'.

In my product list compnent

        ngOnInit(): void {
            this._getPro();
            this._getCate();
        }
        private _getPro(categoriesFilter?: string[]) {
            this.proService.getProducts(categoriesFilter).subscribe((pros) => {
                this.products = pros;
            });
        }
        private _getCate() {
            this.catService.getCategories().subscribe((cate) => {
                this.categories = cate;
            });
        }
        categoryFilter() {
            const selectedCategories = this.categories
                .filter((cate) => cate.checked)
                .map((cate) => cate.id);
            this._getPro(selectedCategories);
        }
    }

In my product service

//get all


     getProducts(categoriesFilter?: string[]): Observable<Product[]> {
            let params = new HttpParams();
            if (categoriesFilter) {
                params = params.append('categories', categoriesFilter.join(','));
            }
            return this.http.get<Product[]>(this.apiURLProducts, { params: params });
        }

this error here


Solution

  • You can add another filter criterion to ensure that the id property is set on each category, and make the filter function a type guard predicate function:

    TS Playground

    categoryFilter() {
      const selectedCategories = this.categories
          .filter((c): c is typeof c & {
            checked: true;
            id: string;
          } => Boolean(c.checked && c.id))
          .map(({id}) => id);
      this._getPro(selectedCategories);
    }