Home > Net >  Why my property does not exist on type 'never'
Why my property does not exist on type 'never'

Time:09-13

I'm trying to type a ts file which is for some slices in react js using redux. The problem is that I keep having this error : "Property 'quantity' does not exist on type 'never'.".

Here's the code :

addToCart: (state, action) => {
        const itemInCart = state.cart.find(
            (item: Record<string, unknown>) => item.id === action.payload.id
        )
        if (itemInCart) {
            itemInCart.quantity  
        } else {
            state.cart.push({ ...action.payload, quantity: 1 })
        }
    },

I tried to add the Record<string, unknown> type but this doesn't make any changes. Do you have any suggestions ?

CodePudding user response:

By typing item as Record<string, unknown> you're typing any property of item to be unknown. This means item.id and itemInCart.quantity are both unknown types. You can not increment an unknown type.

Quick fix If you don't mind switching to type-less code, you can change Record<string, unknown> to Record<string, any> and it would work. Or if that doesn't work you can try changing const itemInCart to const itemInCart: any.

Better fix Create a type or interface for items in your cart. E.g:

interface CartItem {
   id: string;
   quentity: number;
}

(I'm assuming here that id is a string, you can change it to whatever is the actual type) And then use Record<string, CartItem>

CodePudding user response:

Try writing it like this:

const [arr, setArr] = useState<any[]>([])
  • Related