Typescript error 'argument of type is not assignable to parameter of type'

Viewed 1047

I'm relatively new to TS, and I'm running into a weird issue. I seem to have defined everything, but it doesn't seem to recognize my typing for the data.

Here is what I have:

const Component = () => {
    const [data, setData] = React.useState([[], []])

    React.useEffect(() => {
        fetchData()
    }, [])

    const fetchData = React.useCallback(async () => {
        const data = await fetchDataController()

        setData(data)
                ^^^^ error
    })
}

This throws the error,

Argument of type 'Element[][]' is not assignable to parameter of type 'SetStateAction<never[][]>'
  Type 'Element[][]' is not assignable to type 'never[][]'
    Type 'Element[]' is not assignable to type 'never[]'
      Type 'Element is not assignable to type 'never'

My function fetchDataController return an array of arrays of elements.

My type is as follows:

type TData = {
  id: string,
  desc: string
}

I've tried doing something like,

const [data, setData] = React.useState<Array<TData[], TData[]>>([[], []])

But that didn't seem to work. What am I missing here?

1 Answers

You were close. Array<...> requires one argument, the type of items in the array. So you could do something like Array<TData[]>. If you don't want to use Array<...>, you could do something like TData[][] as well

So,

React.useState<TData[][]>([[], []])

Here's a working codesandbox with some mocks


If you want to be more specific, and define it as a Tuple, instead of usual array:

React.useState<[TData[], TData[]]>([[], []])

but for that to work, you'll have to assure Typescript that what you are setting i.e. data in setData(data) is also of type [TData[], TData[]].

You can do that with something like setData(data as [TData[], TData[]])

Related