0
votes

I'm facing an issue with Typescript and the nuxt-composition-api plugin.

I have a composition function that I use to fetch data for multiple table views in my app. I want to use Typescript generics to give the composition function the type of data it will be fetching so I can then enjoy type inference in my components.

The problem is that my items are stored as an array in a reactive object's key, and when I want to update the state with the data i fetched from the API, I end up with a TS error like the one in the code below.

I've read throug multiple SO and GH posts and issues and couldn't find anything to help with that. Do you have any idea how I could solve this ?

import { onMounted, reactive, useContext } from '@nuxtjs/composition-api'
import { PaginatedResponse } from '~/helpers/api'

export interface TableHook<T> {
  state: TableState<T>
  // Some more types
}

export interface TableState<T> {
  items: T[]
  // Some more types
}

function useTable<T>({ baseUrl }: { baseUrl: string }): TableHook<T> {
  const { app: { $api } } = useContext()


  const state = reactive<TableState<T>>({
    items: [] as T[]
    // Some more keys, related to pagination and loading state
  })

  onMounted(() => {
    fetchPage()
  })

  async function fetchPage() {
    const res: PaginatedResponse<T> = await $api.get(baseUrl)
    // The following statement throws a TS error
    // Type 'T[]' is not assignable to type 'UnwrapRefSimple<T>[]'.
    // Type 'T' is not assignable to type 'UnwrapRefSimple<T>'.ts(2322)
    state.items = res.data // res.data is infered as T[]
  }

  // Some more methods here...

  return {
    state
  }
}

export default useTable

My PaginatedResponse interface looks like this :

export interface PaginatedResponse<T> {
  current_page: number | null
  data: T[]
  next_page: number | null
  per_page: number | null
  prev_page: number | null
  total: number | null
}
1
Good questioning & code format. Can you post the PaginatedResponse type? - Felipe Malara
Sure, it's basically an interface with a generic type param to describe what the pagination response from my API looks like. I updated the question. But, as stated in the answer below, I believe I solved the issue with a cast. - Kerunix

1 Answers

0
votes

I managed to solve the issue by casting state to uknown then to TableState like so :

  const state = (reactive<TableState<T>>({
    items: [] as T[],
  }) as unknown) as TableState<T>

I don't know if it is the right solution but my error went away and I have access to type inference and autocompletion in my components.