[英]Missing properties for type (typescript)
In the following:在下面的:
@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--);
...
gives:给出:
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--);
What type does the reducer return?减速机返回什么类型?
Products are objects that need to be indexed over their id;产品是需要在其 id 上建立索引的对象; eg
例如
[{
id: 1,
productName: "coke",
productPrice: 2,
productQty: 20
},
...
]
reducedProductsInVendingMachine
is not an Array
, its an Object
. reducedProductsInVendingMachine
不是一个Array
,它是一个Object
。
One possibility is to cast {}
to the correct type in the initialization parameter of Array.prototype.reduce()
:一种可能性是将
{}
转换为Array.prototype.reduce()
的初始化参数中的正确类型:
const reducedProductsInVendingMachine =
tmpProductsInVendingMachine.reduce(
(tmpProductsInVendingMachine, { id, ...rest }) =>
({ ...tmpProductsInVendingMachine, ...{ [id]: { id, ...rest } } }),
{} as { [key: I.Product['id']]: I.Product }
);
Notice how the implementation compiles and the reducedProductsInVendingMachine
variable type is correctly inferred to { [key: I.Product['id']]: I.Product }
(with I.Product['id']
resolved to whatever it is)注意实现是如何编译的,并且
reducedProductsInVendingMachine
变量类型被正确推断为{ [key: I.Product['id']]: I.Product }
( I.Product['id']
解析为它是什么)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.