Search code examples
angulartypescripttypescript-generics

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


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?


Solution

  • Body is an optional attribute, to declare to TS that it's an array you can use instanceof operator.

    if (response.body instanceof Array) {
       this.stocks = response.body
    } else {
       this.stocks =[]
    }