TS 自动推导的问题?

hook 里我想根据是否存入 transformData 函数,自动推导出返回的 tableData 的类型,现在的问题是,当我传入 transformData 时,tableData 的类型是 (T | R)[] , 如果我不传 transformData, tableData 的类型是 (T|(R 的默认值))[] , 如何才能在传入transformDatatableData 得到 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 }))
})

求助各位大佬

阅读 660
2 个回答
declare function f<T extends [] | [number]>(...args: T): T extends [] ? 1 : 2


const a = f()  // 1
const b = f(123)  // 2
function foo<T, R = T>(a: T, b?: (v: T) => R): R {
  if (b) return b(a);
  return a;
}

这样不就行了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏