Home > OS >  how to add type to react useReducer reducer function?
how to add type to react useReducer reducer function?

Time:07-29

I have this useReducer function in pure react without type script now I would like to add types to it.

useReducer reducer function with pure react without types

export const cartReducer = (state, action) => {
  switch (action.type) {
    case "ADD_TO_CART":
      return { ...state, cart: [...state.cart, { ...action.payload, qty: 1 }] };
 
    default:
      return state;
  }
};

Here is what I have tried so far adding types to reducer function

import { IProduct } from "../context/Context";

export interface IState {
    products: IProduct[];
    cart: [];
}

export type Actions =
    | {type:"ADD_TO_CART", payload:number}
    | {type:"REMOVE_FROM_CART", payload:number}
    | {type: "CHANGE_CART_QTY", payload: number }


export const cartReducer = (state:IState, action:Actions): IState =>{
    console.log('state', state)
    switch (action.type) {
        case "ADD_TO_CART":
            console.log('ADD_TO_CART')
            return {
                ...state,
                cart: [...state.cart, { ...action.payload, qty: 1}]
              };
    
        default:
            return state;
    }
}
  1. TS2322: Type '[any]' is not assignable to type '[]'.
    
 TS2698: Spread types may only be created from object types.

enter image description here

CodePudding user response:

You have two problems:

The first one is you defined your cart type as [] which means that the only possible value for that is an empty list. If your list will consist of multiple objects, your type may become:

export interface IState {
    products: IProduct[];
    cart: {payload: number, qty: number}[];
}

But then comes problem two, you are spreading a number which is incorrect, probably you incorrectly defined that interface as you say your JS code is working. If it's correct, then instead of:

 cart: [...state.cart, { ...action.payload, qty: 1}]

you should do

 cart: [...state.cart, { payload: action.payload, qty: 1}]
  • Related