首页 > 解决方案 > 将数组类型初始化为对象javascript

问题描述

我有一个名为 Products 的界面

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

我的产品数组类型的组件中有一个变量

products: Products[];

我正在尝试将我的服务响应映射到 products 变量,但我收到此错误类型

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

我不知道我做错了什么

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

标签: javascripttypescriptfirebase-realtime-databaseangular8

解决方案


在这个赋值子句中:

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

...您将其转换p.payload.val()为类型{}并将其传播到一个空对象中(以克隆它?),该对象仍将其类型保持为{}. 因此,products.map(...)具有 的类型{}[],也称为Array<{}>。因为this.products是 a Product[],所以类型不兼容。

如果p.payload.val()已经是 type Product,则无需强制转换任何内容:

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

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

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

如果它不是type 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
});

推荐阅读