1

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 {}) }))),
  )
6
  • 1
    What does your method p does? (Within the map function) Commented Apr 14, 2020 at 19:29
  • sorry that's a mistake. should be p => ({...p.payload.val() as {}} Commented Apr 14, 2020 at 19:49
  • Does something called payload have a method? Most payloads I've seen are plain data objects. Commented Apr 14, 2020 at 19:50
  • @gbubemismith does the p refer to products? Commented Apr 15, 2020 at 19:26
  • 2
    You're explicitly doing an as {} in there; do you mean to do as Product or leave off the as clause if it's type inferable? You're basically telling the compiler to make an {}[]. Commented Apr 15, 2020 at 19:27

1 Answer 1

1

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 {}[], a.k.a. 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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.