How to set a state variable to an empty array in React Typescript

I have a simple useState function that looks like this:

const [value, setValue] = useState<values[]>([]);

Theoretically, this will mean that the state of value defaults to an empty array.

I then have a function that I’ve defined like this:

  function handleSelectValue(id: string) {
      let fakeArray:Array<values> = [...Value, DefinedArray.find(x =>]

I also tried:

  function handleSelectValue(id: string) {
      setValue([...Value, DefinedArray.find(x =>]);

I would think that this code should work, however, I get an error that says

Type ‘Value | Undefined’ is not assignable to type ‘Value’. Type ‘Undefined’ is not assignable to type ‘Value’.

I’m not sure where, exactly, the undefinedness is coming from. It seems to me that my default value of "value" is defined as an empty array of value. (Value is defined elsewhere, to be clear, with a Guid, a name, and a few other descriptor fields).

What is wrong with this code here? I know stateful arrays can be a bit wonky, but this seems pretty straightforward to me.

>Solution :

find() returns undefined if it can’t find anything.

undefined is not compatible with your typing. So you should only append it here is something to append:

function handleSelectValue(id: string) {
      const findResult = DefinedArray.find(x =>;
      if (findResult) {
            setValue([...Value, ...findResult ]);

Or you could spread an empty array as fallback, if that’s more readble:

setValue([ ...Value, ...(DefinedArray.find(x => || []) ]);

Leave a Reply