gpt4 book ai didi

javascript - 源有 2 个元素,但目标只允许 1 个。Typescript 扩展运算符

转载 作者:行者123 更新时间:2023-12-05 00:44:06 25 4
gpt4 key购买 nike

我正在尝试在数组中传播所有值并在我的 reducer 中附加一个新对象。

我的状态界面:

export interface IBasketState {
products: [
{
id: number | undefined;
name: string;
smallQ: number; //small packages quantity
smallTotalP: number; //price for all small packages
largeQ: number; //large packages quantity
largeTotalP: number; //price for all large packages
orderPrice: number; //total price of this order
}
];
totalPrice: number;
}

Reducer添加item功能:

const BasketReducer = (basketState: IBasketState, action: IBasketAction): IBasketState => {
//ADD ITEM
if (action.type === "Add item") {
const { id, name, smallQ, smallP, largeQ, price } = action.payload;
let smallTotalPrice = smallQ * smallP; //total price for small packages
let largeTotalPrice = largeQ * price; //total price for large packages
const orderPrice = smallTotalPrice + largeTotalPrice; //total price of this order
return {
products: [
...basketState.products, //--> **THIS IS NOT WORKING**
{
id: id,
name: name,
smallQ: smallQ,
smallTotalP: smallTotalPrice,
largeQ: largeQ,
largeTotalP: largeTotalPrice,
orderPrice: orderPrice,
},
],
totalPrice: basketState.totalPrice + orderPrice,
};
}
//Default action
return basketState;
};

当我将鼠标悬停在 ...basketState.products 上时,我收到一条错误消息:

输入 '[{ id: number |不明确的;名称:字符串;小Q:数字; smallTotalP:数字;大Q:数字; largeTotalP:数字;订单价格:数量; }, { id: 数字 |不明确的;名称:字符串;小Q:数字; smallTotalP:数字;大Q:数字; largeTotalP:数字;订单价格:数量; }]' 不能分配给类型 '[{ id: number |不明确的;名称:字符串;小Q:数字; smallTotalP:数字;大Q:数字; largeTotalP:数字;订单价格:数量; }]'。

来源有 2 个元素,但目标只允许 1.ts(2322)

BasketContext.tsx(8, 2):预期的类型来自属性“products”,在此处声明的类型为“IBasketState”

问题是在我的界面中我只在 products 数组中声明了一个对象而我现在尝试拥有 2 个吗?如果是这样,我该如何绕过它?

最佳答案

您的猜测是正确的:products 属性被键入为只包含一个元素的元组。

您可以尝试将其变成一系列产品:

interface BasketState {
products: Product[];
totalPrice: number;
}

interface Product {
id: number | undefined;
name: string;
smallQ: number;
smallTotalP: number;
largeQ: number;
largeTotalP: number;
orderPrice: number;
}

您可以在此处阅读有关 TypeScript 元组类型的更多信息:https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types

关于javascript - 源有 2 个元素,但目标只允许 1 个。Typescript 扩展运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68223815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com