Source has 2 element s but target allows only 1 Typescript spread operator

0 votes

I'm trying to spread all values in array and append a new object in my reducer.

my state interface:

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 add item function:

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;
};

When I hover over ...basketState.products I've got an error saying:

Type '[{ id: number | undefined; name: string; smallQ: number; smallTotalP: number; largeQ: number; largeTotalP: number; orderPrice: number; }, { id: number | undefined; name: string; smallQ: number; smallTotalP: number; largeQ: number; largeTotalP: number; orderPrice: number; }]' is not assignable to type '[{ id: number | undefined; name: string; smallQ: number; smallTotalP: number; largeQ: number; largeTotalP: number; orderPrice: number; }]'.

Source has 2 element(s) but target allows only 1.ts(2322)

BasketContext.tsx(8, 2): The expected type comes from property 'products' which is declared here on type 'IBasketState'

Is the problem the fact that in my interface I have declared only one object in products array and I'm trying to have 2 now? If so how can I bypass that?

Aug 3, 2022 in TypeSript by Elton
• 400 points

edited Mar 4 6 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP