Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

525
Views
TS2322: Type 'Product[] | null' is not assignable to type 'Product[]'

Interface:

export interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  imageURL: string;
}

Component:

products: Product[] = [];

  ngOnInit() {
    this.dataService.sendGetRequest().pipe(takeUntil(this.destroy$)).subscribe((res: HttpResponse<Product[]>)=>{
      console.log(res);
      this.products = res.body; // The error is in this place
    })
  }

It throws an error when compiling:

TS2322: Type 'Product[] | null' is not assignable to type 'Product[]'.   Type 'null' is not assignable to type 'Product[]'.

How to fix it?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You have

res: HttpResponse<Product[]>

It means that res if of type Product[]. And then you are assigning

this.products = res.body;

where products is of type product array and res is of type Product[]. Point to note is, Product interface has no body property and hence TS compiler says it can't assign null to products. Try modifying your code like this:

ngOnInit() {
    this.dataService.sendGetRequest().pipe(takeUntil(this.destroy$)).subscribe((res)=> {
      console.log(res);
      this.products = res.body as Product[];
    })
  }
over 4 years ago · Santiago Trujillo Report

0

this.products = res?.body; or this.products = res.body ? res.body : []; will simply solve this problem. But better check the API call, actually why it is sending null as res.body? shouldn't it be an empty array instead?

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!