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

515
Views
TS2322: Tipo 'Producto[] | null' no se puede asignar al tipo 'Producto []'

Interfaz:

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

Componente:

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

Me arroja un error al compilar:

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

¿Como arreglarlo?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Tú tienes

 res: HttpResponse<Product[]>

Significa que res si es de tipo Product[]. Y luego estás asignando

 this.products = res.body;

donde products es de tipo product array y res es de tipo Product[] . El punto a tener en cuenta es que la interfaz del producto no tiene propiedad de cuerpo y, por lo tanto, el compilador de TS dice que no puede asignar valores nulos a los productos. Intenta modificar tu código de esta manera:

 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; o this.products = res.body ? res.body : []; simplemente resolverá este problema. Pero mejor verifique la llamada a la API, ¿por qué está enviando un valor nulo como res.body ? ¿No debería ser una matriz vacía en su lugar?

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!