user14899645
user14899645

Reputation:

Defining a type for state and action Typescript

I am using state and action in a typescript file, which looks like this:

export const CartReducer = (state, action) => {
     switch (action.type) {
         case "ADD_ITEM":
             if (!state.cartItems.find(item => item.id === action.payload.id)) {
                 state.cartItems.push({
                     ...action.payload,
                     quantity: 1
                 })
             } 
 
             return {
                 ...state,
                 ...sumItems(state.cartItems),
                 cartItems: [...state.cartItems]
             }
         case "REMOVE_ITEM":
             return {
                 ...state,
                 ...sumItems(state.cartItems.filter(item => item.id !== action.payload.id)),
                 cartItems: [...state.cartItems.filter(item => item.id !== action.payload.id)]
             }
         case "INCREASE":
             state.cartItems[state.cartItems.findIndex(item => item.id === action.payload.id)].quantity++
             return {
                 ...state,
                 ...sumItems(state.cartItems),
                 cartItems: [...state.cartItems]
             }
         case "DECREASE":
             state.cartItems[state.cartItems.findIndex(item => item.id === action.payload.id)].quantity--
             return {
                 ...state,
                 ...sumItems(state.cartItems),
                 cartItems: [...state.cartItems]
             }
         case "CLEAR":
                 return {
                     cartItems: [],
                     ...sumItems([]),
                 }
         default:
             return state
 
     }
 }

I am getting the following error:

src/contexts/CartReducer.tsx:28:30
TS7006: Parameter 'state' implicitly has an 'any' type.
    26 |  }

I am not sure of how to define type for State and Action, while I have declared types for other elements, I am not of the same for State and Action.

i am trying to follow this, for a typescript project.

Upvotes: 0

Views: 559

Answers (2)

Akxe
Akxe

Reputation: 11475

You are following JS-only project, try following a typescript project.

interface MyState {
  readonly cartItems: readonly any[];
  ...
}
type Reducer<T> = (currentState: T, action: { type: string, payload: any })

export const CartReducer: Reducer<MyState> = (state, action) => { ... }

Try to look for types for reducer/action for React. Better than reinvent the wheel.

Upvotes: 1

Jamie T
Jamie T

Reputation: 56

I believe you need to define an InitialState

initialState = {
cartItems:[]
}

export const CartReducer = (state=initialState , action) => {
 switch (action.type) {

Upvotes: 0

Related Questions