I'm new to TypeScript and I'm encountering this error that I don't know how to solve.
My project is React Redux Toolkit and the error is thrown out just in a cartSlice.ts:
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
interface CartState {
name: string
initialState: {
cart: {}[]
}
}
export const cartSlice = createSlice({
name: 'cart',
initialState: {
cart: [],
},
reducers: {
addToCart: (state, action) => {
const itemInCart = state.cart.find(
(item:any) => item.id === action.payload.id
)
if (itemInCart) {
itemInCart.quantity ;
} else {
state.cart.push({ ...action.payload, quantity: 1 })
}
},
removeItem: (state, action) => {
const removeItem = state.cart.filter((item) => item.id !== action.payload)
state.cart = removeItem
},
},
})
export const cartReducer = cartSlice.reducer
export const { addToCart, removeItem } = cartSlice.actions
The errors that I'm encountering:
Property 'quantity' does not exist on type 'never'.
Type 'number' is not assignable to type 'never'.
Property 'id' does not exist on type 'never'.
Any clue?
Your help is much appreciated!
CodePudding user response:
Because you didn't define it inside initialState and settled for the object {}[].
your interface may look like this:
type TCart = {
id?: string;
quantity?: number;
};
interface CartState {
name: string;
initialState: {
cart: TCart[];
};
}
CodePudding user response:
The problem is here :
cart: {}[]
The never type represents the type of values that never occur.
Cart is inferred to be an array of objects with zero keys. According to TS, there is no way you will find an element using this because id
key does not exist on any item in cart
array.
const itemInCart = cart.find(
(item:any) => item.id === 1
);
So itemInCart
type is inferred to be never
. And quantity
key does not exist on never.
This is why you get both these errors:
Property 'quantity' does not exist on type 'never'.
Property 'id' does not exist on type 'never'.
Similarly, the following statement
state.cart.push({ ...action.payload, quantity: 1 })
causes
Type 'number' is not assignable to type 'never'.
Do something like:
interface CartState {
name: string
initialState: {
cart: { quantity : number ,id : number }[]
}
}