skip to Main Content

I am getting this error Argument of type 'MyInterface[]' is not assignable to parameter of type 'SetStateAction<MyInterface | null>. I am unsure of what to do here. I feel like I have run into this before, but unsure of what I did to resolve it. Here is what I have:

interface MyInterface {
  email: string;
  name: string;
}

const [selection, setSelection] = useState<MyInterface | null>(null);

//defaultValue is being populated from a query pull and it is of type MyInterface[]

useEffect(() => {
   setSelection(defaultValue);
 }, []);

2

Answers


  1. Argument of type 'MyInterface[]'
    //                -----------^^
    
    is not assignable to parameter of type 'SetStateAction<MyInterface | null>.
    //                                                     ---------^^
    

    See the problem now?


    You have a state that is a MyInterface, but you are trying to assign an array of MyInterface to that state.

    So you probably want to type your state to accept MyInterface[] instead.

    const [selection, setSelection] = useState<MyInterface[] | null>(null);
    

    See Playground

    Login or Signup to reply.
  2. Fixing ‘Argument Not Assignable’ Error in React

    You’re running into a classic issue with type mismatches in TypeScript. Let’s break it down:

    Your state, selection, is set up to hold either a single object of type MyInterface or null. But the value you’re trying to assign to it, defaultValue, is an array of MyInterface objects. Imagine it’s like trying to fit a whole tray of cups into a single cup holder. It won’t work.

    Let’s solve this issue:

    1. If you want selection to store just one MyInterface object:
    Pick the first object from defaultValue:

    setSelection(defaultValue[0]);
    

    However if there is the possibility defaultValue could be empty, play it safe:

    setSelection(defaultValue.length > 0 ? defaultValue[0] : null);
    

    2. If you would like selection to be able to hold the whole array:
    You need to modify how you have set up the state so an array of MyInterface objects or null is expected:

    const [selection, setSelection] = useState<MyInterface[] | null>(null);
    

    Now with those changes, assigning defaultValue to selection should work correctly:

    setSelection(defaultValue);
    

    Which options you select depends on your use-cases. Certainly, the key is to ensure proper alignment between the types of values you’re dealing with.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search