簡體   English   中英

Vue 組合 api 數組在反應 object 打字錯誤

[英]Vue composition api array in reactive object typing error

我遇到了 Typescript 和 nuxt-composition-api 插件的問題。

我有一個組合 function 用於在我的應用程序中獲取多個表視圖的數據。 我想使用 Typescript generics 為組合 function 提供它將獲取的數據類型,這樣我就可以在我的組件中享受類型推斷了。

問題是我的項目作為數組存儲在反應對象的鍵中,當我想用從 API 獲取的數據更新 state 時,我最終會出現 TS 錯誤,就像下面代碼中的錯誤一樣。

我已經閱讀了多個 SO 和 GH 帖子和問題,但找不到任何幫助。 你知道我該如何解決這個問題嗎?

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

我的 PaginatedResponse 界面如下所示:

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
}

我設法通過將 state 轉換為 uknown 然后轉換為 TableState 來解決該問題,如下所示:

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

我不知道這是否是正確的解決方案,但我的錯誤消失了,我可以訪問組件中的類型推斷和自動完成功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM