TS2322: Type '{ headers: HttpHeaders; body: Stock[]; } | null' is not assignable to type...

Discussão em 'Angular' iniciado por Singleton, Janeiro 14, 2025.

  1. Singleton

    Singleton Guest

    I am getting this TypeScript error in Angular. I have a class named StockComponent with the following property:

    protected stocks: Stock[] = [];

    The Stock class is a regular class I created to represent a Stock entity. I am trying to get this to work:

    this.http.get<{headers: HttpHeaders, body: Stock[]}>('https://www.example.com/wp-json/wp/v2/stock/', {
    observe: 'response'
    }).subscribe((response) => {
    this.total = Number(response.headers.get('X-WP-Total'));

    this.total_pages = Number(response.headers.get('X-WP-TotalPages'));

    this.stocks = response.body;
    });


    I see this error when I try assigning the body to this.stocks. The problem resolves if I change Stock[] = [] to Stock[]|any = []

    How can I make this work right?

    Continue reading...

Compartilhe esta Página