【问题标题】:Missing properties for type (typescript)缺少类型的属性(打字稿)
【发布时间】: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


【解决方案1】:

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'] 解析为任何类型)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-18
    • 2021-09-23
    • 2017-12-22
    • 2023-02-07
    • 2021-04-29
    • 2013-09-17
    • 2019-05-02
    • 1970-01-01
    相关资源
    最近更新 更多