【问题标题】:Initializing an array type to an object javascript将数组类型初始化为对象javascript
【发布时间】:2020-04-16 06:54:37
【问题描述】:

我有一个名为 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 {}) }))),
  )

【问题讨论】:

  • 你的方法p是做什么的? (地图功能内)
  • 对不起,这是一个错误。应该是 p => ({...p.payload.val() as {}}
  • 有没有一个叫做payload的东西有一个方法?我见过的大多数有效载荷都是纯数据对象。
  • @gbubemismith p 指的是产品吗?
  • 你在里面明确地做了一个as {};如果类型可推断,您是要执行as Product 还是放弃as 子句?您基本上是在告诉编译器生成{}[]

标签: javascript typescript firebase-realtime-database angular8


【解决方案1】:

在这个赋值子句中:

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

...您将p.payload.val() 转换为{} 类型,并将其传播到一个空对象中(克隆它?),它仍然保持其类型为{}。因此,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
});

【讨论】:

    猜你喜欢
    • 2012-10-31
    • 2018-06-22
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 2020-03-19
    相关资源
    最近更新 更多