patterntypescriptangularCritical
Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]
Viewed 0 times
typescriptfrommoreand2740propertiesthemissingpushconcat
Problem
I have this Product interface:
Service with method calling product endpoint:
And component where I use this service to get the Products.
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
export interface Product{
code: string;
description: string;
type: string;
}Service with method calling product endpoint:
public getProducts(): Observable {
return this.http.get(`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?Solution
You are returning
The Type returned from
Observable and expecting it to be Product[] inside subscribe callback.The Type returned from
http.get() and getProducts() should be Observablepublic getProducts(): Observable {
return this.http.get(`api/products/v1/`);
}Code Snippets
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}Context
Stack Overflow Q#54475893, score: 164
Revisions (0)
No revisions yet.