The parameter cannot be assigned to type 'string[]' because its argument is of type '(string | undefined)[]'

I encountered an issue with my code involving angular 13 and string[]

The error message reads: "Argument of type '(string | undefined)[]' is not assignable to parameter of type 'string[]'."

This problem occurs in my product list component.

        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);
        }
    }

The issue also persists 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 });
        }

View the screenshot of the error here

Answer №1

To ensure that each category has the id property set, you can include an additional filter criterion and transform the filter function into 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);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for conducting a worldwide search in Angular 2?

I'm currently navigating my way through angular2 development and I am aiming to conduct a comprehensive search within an array of JSON objects. To illustrate, consider this sample array: invoiceList = [ { invoiceNumber: 1234, invo ...

Guide on integrating a dynamic element within another element in Angular

Imagine a scenario where we have the following html structure <div [innerHTML]="contentFromAPI | safeHTML"></div> The content retrieved from the api contains multiple HTML elements, resulting in a structure like this: <div> &l ...

My component reference seems to have gone missing in angular2

Trying to load my Angular 2 app, I encountered this error: https://i.stack.imgur.com/FmgZE.png Despite having all the necessary files in place. https://i.stack.imgur.com/kj9cP.png Any suggestions on how to resolve this issue? Here is a snippet from ap ...

Managing the outcome of numerous asynchronous calls before accessing the database post-result collection

Hey everyone, I'm just getting started with node.js and I'm working on the following tasks: Calling the AWS API to create Cognito users by passing data. After all requests are completed, inserting all the records into the database. In my code, ...

Why does the error message "DeprecationWarning: 'originalKeywordKind' deprecated" keep popping up while I'm trying to compile my project?

Upon completing the compilation of my project, I encountered the error message provided below. What does this signify and what steps can I take to resolve it? - info Linting and checking validity of types DeprecationWarning: 'originalKeywordKind' ...

Maintaining ongoing subscriptions using rxjs in Angular 5

As a newcomer to rxjs in Angular 5, I find it a bit challenging to articulate my question, but I am hopeful for some guidance. I frequently encounter the same setup: Multiple Components to display identical data A single Service for accessing the data ...

Developing a dynamic object deserializer in TypeScript/Angular 2

My background is in C# where I have experience working in a dynamic and reflective manner. Now, I am transitioning to TypeScript for writing a class and trying to apply similar principles. To provide context, I am converting an existing application into a ...

Strategies for Safely Assigning Firestore Data to an Object Without Losing Null Values

I am dealing with a class setup as follows: export class Car{ color=''; topSpeed=0; wheels = 4; } Within my Firestore database, there exists a document titled "car" with values: color:red topSpeed:230 (note that the 'wheels&a ...

What is the best way to compare two sets of arrays and generate a new one with unique key-value pairs?

I have two arrays and I want to extract specific key-value pairs from each and combine them into a new array, handling duplicate entries. First Array : [ {id: 2, name: "HSBC", status: "YES"}, {id: 3, name: "Morgan Stanley&quo ...

Tips for sending a function with arguments in a React application using TypeScript

Is there a way to streamline passing a handleClick function to the son component so that it does not need to be repeated? The code in question is as follows: Mother Component: const Mother = () => { const [selectedOption, setSelectedOption] = useSt ...

Fixing the Bootstrap 4 issue "Popper.js required for Bootstrap dropdowns" using Aurelia CLI and Require.js

Struggling to set up Bootstrap 4 beta in an Aurelia CLI app (v0.31.1) with requirejs and TypeScript. Despite trying different configurations, the console consistently shows this error: Uncaught Error: Bootstrap dropdown require Popper.js Here's a ...

The message "The property 'layout' is not found on the type 'FC<WrapperProps>' in Next.js" is displayed

I encountered an error in my _app.tsx file when attempting to implement multiple layouts. Although the functionality is working as expected, TypeScript is throwing an error Here is the code snippet: import Layout from '@/components/layouts&apo ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Screen a collection of strings based on the matching character at the corresponding position

In an attempt to create a basic function that takes in three inputs: a list of words, a list of guessed letters, and a pattern. The pattern represents a word with certain letters hidden as underscores (for example, the word "apple" and the pattern "_pp_e") ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...

Error: Installation of package was unsuccessful. Please refer to the above error message for details. The Schematic process encountered an issue

After attempting to create a new project using the command ng new project-1, I encountered an error message. × Package install failed, see above. The Schematic workflow failed. See above. Even after updating Node to the latest version, the error persist ...

Is it necessary to implement ngOnDestroy for subjects in Angular?

Is it necessary to manually unsubscribe using the ngOnDestroy hook when using the subject in Angular, or does Angular handle the unsubscribing automatically? ...

Incorporating types and optional arguments in Typescript programming

Develop a program using JavaScript to display all the properties of a given object Example object: var student = { name : "David Rayy", sclass : "VI", rollno : 12 }; Your task is to enhance this program by incorporating typing, optional arguments, an ...

Utilizing PropTypes in React with TypeScript

I've encountered issues while trying to integrate PropTypes with Typescript: Previously, without typescript, I had successfully used: class TodoFilterItem extends Component { constructor (props) { super(props); Followed by: TodoFilterItem.prop ...

Jhipster has issues with the functionality of the Bootstrap dropdown

<div class="form-group"> <div class="dropdown-example"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example ...