【发布时间】:2022-01-17 06:43:19
【问题描述】:
如下:
@Mutation
remove_bought_products(productsToBeRemoved: Array<I.Product>) {
const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine);
const reducedProductsInVendingMachine: Array<I.Product> =
tmpProductsInVendingMachine.reduce((tmpProductsInVendingMachine, { id, ...rest }) => ({ ...tmpProductsInVendingMachine, ...{ [id]: { id, ...rest } } }), {});
productsToBeRemoved.forEach(({ id }) => reducedProductsInVendingMachine[id].productQty--);
...
给予:
TS2740: Type '{}' is missing the following properties from type 'Product[]': length, pop,
push, concat, and 28 more.
250 |
251 | const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine);
> 252 | const reducedProductsInVendingMachine: Array<I.Product> =
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
253 | tmpProductsInVendingMachine.reduce((tmpProductsInVendingMachine, { id, ...rest }) => ({ ...tmpProductsInVendingMachine, ...{ [id]: { id, ...rest } } }), {});
254 | productsToBeRemoved.forEach(({ id }) => reducedProductsInVendingMachine[id].productQty--);
reducer 返回什么类型?
产品是需要在其 id 上建立索引的对象;例如
[{
id: 1,
productName: "coke",
productPrice: 2,
productQty: 20
},
...
]
【问题讨论】:
-
您在这里犯了一个非常基本的错误,因为您不熟悉 reduce 对数组的作用。但是,如果您没有在局部变量上放置完全不必要的类型注释,您就会发现这一点。类型推断是您的朋友,尤其是在您找出 API 时。
-
您没有使用 reduce 创建数组,因此会出现问题。它返回最后一个参数
{}。如果期望输出是一个与输入元素数量相同的数组,请考虑改用map -
@AluanHaddad 在这种情况下它给出“对象可能未定义”错误
标签: javascript arrays typescript vue.js types