Reputation: 21
I'm new to Typescript and react and am getting this error, on default card
I am trying to setup use context and will use it with use state or use reducer but I am having trouble wrapping my head around initial setup for this
Error:
Argument of type '{ cartitem: { id: number; name: string; description: string; price: string; }; addCart: () => void; removeCart: () => void; }' is not assignable to parameter of type 'CartContextType'.
Types of property 'cartitem' are incompatible.
Type '{ id: number; name: string; description: string; price: string; }' is missing the following properties from type 'ICart[]': length, pop, push, concat, and 29 more.ts(2345)
import React, { createContext } from 'react';
export interface ICart {
id: number;
name: string;
description: string;
price: string;
}
export type CartContextType = {
cartitem: ICart[];
addCart: (cart: ICart, totalAmount:number) => void;
removeCart: (id: number) => void;
};
const defalutCart={cartitem:{
id: 0,
name: 'string',
description: 'string',
price: 'string'},
addCart: () => {},
removeCart: () => { }
}
export const CartContext = createContext<CartContextType | null>(defalutCart);
Upvotes: 2
Views: 75
Reputation: 1424
Your variable defalutCart
needs the property cartitem
to be an array. With the correct spelling and changes, here is your updated code:
const defaultCart = {
cartitem: [
{
id: 0,
name: "string",
description: "string",
price: "string",
},
],
addCart: () => {},
removeCart: () => {},
};
Do you see how the object is now wrapped in an array? Please mark this as correct if it solves your problem.
Upvotes: 1