javascript - 将数组类型初始化为对象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 {}) }))),
)
解决方案
在这个赋值子句中:
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
});
推荐阅读
- sql - 计算每个类别中的员工(两个表)
- android - 截取屏幕截图,然后存储在外部存储中,然后共享
- javascript - 在jade/pug视图中从mysql中拆分数据
- javascript - 完整日历未显示动态生成的事件
- python - 如何在 Scarpy 中使用 Xpath 选择器选择整个内容
- vim - vim + ESLint:用项目特定的文件覆盖默认的 .eslint 文件
- zsh - $BASH_REMATCH[] 的 zsh 等价物是什么?
- java - 带有代理授权的分叉部署过程的 Maven 发布问题作为参数失败,需要 407 代理授权
- c# - 使用来自数据读取器的检查空值更新表
- php - 如何在 WordPress 中获得正确的滑块