Home > Back-end >  Typescript - setState callback function
Typescript - setState callback function

Time:10-14

I am trying to add types to the argument of a callback function within a setState function that updates its previous value (see below). The argument "previous" has to adhere to the "Previous" type; yet when writing that, I get the following error:

Argument of type '(previous: Previous) => { oneArg: number; anotherArg: number; }[]' is not assignable to parameter of type '[] | { oneArg: number; anotherArg: number; }[]'. Type '(previous: Previous) => { oneArg: number; anotherArg: number; }[]' is missing the following properties from type '{ oneArg: number; anotherArg: number; }[]': pop, push, concat, join, and 28 more.ts(2345)

Anybody could help me out?

type Previous = {
  oneArg: number;
  anotherArg: number;
}[] | [];


type Props = {
setState: (arg: { oneArg: number; anotherArg: number }[] | []) => void;
}

function myFunction(someArg: number) {
    props.setState((previous) => {
      return previous.filter((element, index) => {
          return index !== someArg;
        },
      );
    });
  }

CodePudding user response:

I think you need to specify the type of previous. e.g. props.setState((previous: Previous) => {

I'm not sure why you've added | []

I also would have expected you to use the type you defined here

type Props = {
setState: (arg: Previous) => void;
}

For simplicity I would be inclined to make your type:

type Previous = { oneArg: number; anotherArg: number; }

and then using it as follows: setState: (arg: Previous[]) => void;

CodePudding user response:

I figured out the problem: Basically, the type of setState should come from React: Dispatch<SetStateAction<Previous>> where you have to perform the following import (in addition to importing useState): import { Dispatch, SetStateAction} from 'react';

The setState function will then have no problem in taking either an array of objects (in this example) or a callback function as argument.

Also, as Damian was pointing out, | [] in the Type definition was unnecessary, at it is an implied possibility of { oneArg: number; anotherArg: number; }[]

When hovering now over the argument 'previous' in the expression: props.setCart((previous) => {}) TS infers 'previous' to be of Type 'Previous'.

  • Related