Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

527
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda