Home > Net >  How to make TypeScript acceppt setState callback in React Hooks?
How to make TypeScript acceppt setState callback in React Hooks?

Time:07-14

everyone! I'm trying to define my component types using TypeScript and I want to make it so that I can pass either an array of objects or the callback function containing the previous state. This is my code:

type ChipsContextData = {
    chips: Array<ChipsData>,
    setChips: (newChips: Array<ChipsData>) => void | ((setCallback: (previousState: ChipsData[]) => ChipsData[]) => void); 
    counters: Array<number>;
    setCounters: (newCounters: Array<number>) => void; 
}

But TypeScript won't let me use the second part of the union. What can I do?

CodePudding user response:

You need to properly wrap(with braces) each type in union, like this:

type ChipsContextData = {
  chips: Array<ChipsData>;
  setChips:
    | ((newChips: Array<ChipsData>) => void)
    | ((setCallback: (previousState: ChipsData[]) => ChipsData[]) => void);
  counters: Array<number>;
  setCounters: (newCounters: Array<number>) => void;
};

UPDATED

But if you want either an array of objects or the callback function containing the previous state as you said in OP, which is by the way completely different from what you did, then do like this:

type ChipsContextData = {
  chips: Array<ChipsData>;
  setChips:
    | Array<ChipsData>
    | (previousState: ChipsData[]) => ChipsData[];
  counters: Array<number>;
  setCounters: (newCounters: Array<number>) => void;
};

CodePudding user response:

If chips, setChips, counters and setCounters are regular states/setStates created using something like this:

const [chips, setChips] = useState<ChipsData[]>([])
const [counter, setCounter] = useState<number>(0)

then, you can create your ChipsContextData type like below, which is the type of React's setState action:

type ChipsContextData = {
  chips: Array<ChipsData>
  setChips: React.Dispatch<React.SetStateAction<Array<ChipsData>>>
  counters: Array<number>
  setCounters: React.Dispatch<React.SetStateAction<number>>
}
  • Related