在下面的:
@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--);
減速機回傳什么型別?
產品是需要對其 id 進行索引的物件;例如
[{
id: 1,
productName: "coke",
productPrice: 2,
productQty: 20
},
...
]
uj5u.com熱心網友回復:
reducedProductsInVendingMachine不是Array,是Object。
一種可能性是{}在 的初始化引數中強制轉換為正確的型別Array.prototype.reduce():
const reducedProductsInVendingMachine =
tmpProductsInVendingMachine.reduce(
(tmpProductsInVendingMachine, { id, ...rest }) =>
({ ...tmpProductsInVendingMachine, ...{ [id]: { id, ...rest } } }),
{} as { [key: I.Product['id']]: I.Product }
);
注意實作reducedProductsInVendingMachine是如何編譯的,變數型別是如何正確推斷的{ [key: I.Product['id']]: I.Product }(I.Product['id']決議為任何值)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/381425.html
標籤:javascript 数组 打字稿 Vue.js 类型
