簡體   English   中英

將數組類型初始化為 object javascript

[英]Initializing an array type to an object javascript

我有一個名為 Products 的界面

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

我的產品數組類型的組件中有一個變量

products: Products[];

我正在嘗試 map 我的服務對產品變量的響應,但我收到此錯誤類型

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

我不知道我做錯了什么

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

在這個賦值子句中:

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

...您將p.payload.val()轉換為類型{}並將其傳播到一個空的 object (克隆它?),它仍然保持其類型為{} 因此, products.map(...)的類型是{}[] ,也就是Array<{}> 由於this.productsProduct[] ,因此類型不兼容。

如果p.payload.val()已經是Product類型,則無需轉換任何內容:

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

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

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

如果它不是Product類型,則轉換為Product而不是{}

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

// or if cloning...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM