简体   繁体   中英

Initializing an array type to an object javascript

I hava an interface called Products

 export interface Products{
    category: string;
    imageUrl: string;
    price: number;
    title: string;
 }

I have a variable in my component of type products array

products: Products[];

I am trying to map my response from my service to the products variable, but I get this error Type

'{}[]' is not assignable to type 'Products[]'

and I don't know what i'm doing wrong

this.subscription = this.productService
  .getAll()
  .subscribe(
    products =>
      (this.products = products.map(p => ({ ...(p.payload.val() as {}) }))),
  )

In this assignment clause:

this.products = products.map(p => ({
  ...(p.payload.val() as {})
}))

...you're casting p.payload.val() as type {} and also spreading that into an empty object (to clone it?), which still keeps its type as {} . Therefore, products.map(...) has type of {}[] , aka Array<{}> . Since this.products is a Product[] , the type is incompatible.

If p.payload.val() is already of type Product , then there's no need to cast anything:

this.products = products.map(p => p.payload.val())

// or if you need that cloning stuff...

this.products = products.map(p => ({ ...p.payload.val() }))

If it's not of type Product , cast to Product instead of {} :

this.products = products.map(p => p.payload.val() as Product)

// or if cloning...

this.products = products.map(p => {
  return { ...p.payload.val() } as Product
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM