简体   繁体   English

将数组类型初始化为 object javascript

[英]Initializing an array type to an object javascript

I hava an interface called Products我有一个名为 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我正在尝试 map 我的服务对产品变量的响应,但我收到此错误类型

'{}[]' 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 {} . ...您将p.payload.val()转换为类型{}并将其传播到一个空的 object (克隆它?),它仍然保持其类型为{} Therefore, products.map(...) has type of {}[] , aka Array<{}> .因此, products.map(...)的类型是{}[] ,也就是Array<{}> Since this.products is a Product[] , the type is incompatible.由于this.productsProduct[] ,因此类型不兼容。

If p.payload.val() is already of type Product , then there's no need to cast anything:如果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() }))

If it's not of type Product , cast to Product instead of {} :如果它不是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