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
See the problem now?
You have a state that is a
MyInterface
, but you are trying to assign an array ofMyInterface
to that state.So you probably want to type your state to accept
MyInterface[]
instead.See Playground
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
ornull
. But the value you’re trying to assign to it,defaultValue
, is an array ofMyInterface
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
:However if there is the possibility
defaultValue
could be empty, play it safe: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 ornull
is expected:Now with those changes, assigning
defaultValue
toselection
should work correctly: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.