在 hook
里我想根据是否存入 transformData
函数,自动推导出返回的 tableData
的类型,现在的问题是,当我传入 transformData
时,tableData
的类型是 (T | R)[]
, 如果我不传 transformData
, tableData
的类型是 (T|(R 的默认值))[]
, 如何才能在传入transformData
时 tableData
得到 R[]
, 不传时, tableData
得到 T[]
?
import { GetListFn, PaginationProps, Query } from '@/types/globe'
import { sleep } from 'radash'
type SetMode = 'reset' | 'append'
export default function useTable<
T extends Record<string, any> = Record<string, any>,
Q extends Record<string, any> | undefined = undefined,
R extends Record<string, any> = Record<string, any>
>(config: {
request: (params: Query<Q>) => Promise<CommonResponse<{ records: T[], total: number }>>
search?: Q
getListOnMounted?: boolean
setMode?: SetMode
transformData?: (data: T[]) => R[]
}) {
type InferItem<T, F> = F extends undefined ? T : R
const { request, search = {}, getListOnMounted = true, setMode = 'reset', transformData } = config
...
const tableData = ref([]) as Ref<InferItem<T, typeof transformData>[]>
const getList = async (config?: { mode: SetMode }) => {
...
try {
loading.value = true
const { ok, data } = await request(query)
await sleep(100)
if (ok) {
const responseData = data.data.records || []
if (responseData.length) {
const maybeTransformData = transformData?.(responseData) ?? responseData
tableData.value =
_mode === 'reset' ? maybeTransformData : [...tableData.value, ...maybeTransformData]
} else if (_mode === 'reset') {
tableData.value = []
}
pagination.total = data.data.total ?? 0
noMoreData.value = !responseData.length || tableData.value.length === pagination.total
}
} finally {
loading.value = false
}
}
...
return {
...
tableData,
...
}
}
这是我的使用方式
const { tableData } = useTable({
request: (params) => receptionist.list(Number(route.params.id), params),
search: { keyword: '' },
transformData: (data) => data.map((v) => ({ label: v.receptName, value: v.id }))
})
求助各位大佬