Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

I have this Product interface:

export interface Product{   code: string;   description: string;   type: string; } 

Service with method calling product endpoint:

  public getProducts(): Observable<Product> {     return this.http.get<Product>(`api/products/v1/`);   }    

And component where I use this service to get the Products.

export class ShopComponent implements OnInit {     public productsArray: Product[];          ngOnInit() {         this.productService.getProducts().subscribe(res => {           this.productsArray = res;         });     } } 

With this state I'm getting error:

[ts] Type 'Product' is missing the following properties from type 'Product[]': length, pop, push, concat, and 26 more. [2740]

Removing typing on productsArray variable removes the error, but don't get why this is not working, since server response is an array of objects in the type of Products?

like image 488
mpro Avatar asked Feb 01 '19 08:02

mpro


People also ask

Is missing the following properties from type typescript?

The error "Type is missing the following properties from type" occurs when the type we assign to a variable is missing some of the properties the actual type of the variable expects. To solve the error, make sure to specify all of the required properties on the object.

Is missing the following properties from type String []?

js error "Type is missing the following properties from type" occurs when we don't pass any props to a component, or don't pass it all of the props it requires. To solve the error, make sure to provide all of the props that are required in the component. Here is an example of how the error occurs.


1 Answers

You are returning Observable<Product> and expecting it to be Product[] inside subscribe callback.

The Type returned from http.get() and getProducts() should be Observable<Product[]>

public getProducts(): Observable<Product[]> {     return this.http.get<Product[]>(`api/products/v1/`); } 
like image 144
Amit Chigadani Avatar answered Sep 27 '22 18:09

Amit Chigadani