table hooks下的入参类型如何定义ts?
export const useTable = <T = any>( api: (params: any) => Promise<any>,
searchParams?: Recordable,
isPageable: boolean = true,
callback?: (data: any) => any
): TableData<T> => {
const tableData = ref<T[]>([]) as Ref<T[]>
const loading = ref<boolean>(false)
const page = reactive({
current: 1,
limit: 10,
total: 0
})
onMounted(() => getList())
const getList = async () => {
try {
loading.value = true
let { data } = await api({
...searchParams,
current: page.current,
limit: page.limit
})
callback && (data = callback(data))
tableData.value = isPageable ? data.data : data
if (isPageable) page.total = data.total
} finally {
loading.value = false
}
}
如上,我现在规定了返回值的类型,我想约束传入的api的params的类型,该如何实现?我现在定义的是any,我在api文件下对每个api都做了入参的声明,但是我的hooks里我不知道怎么定义,导致我现在觉得我在api文件夹那里做的声明想无用功。我的想法是本身api已经定义了类型参数,能否在hooks里面识别到,并在getList里的api起到约束作用
回答:
你希望hook里面识别到什么呢? api还没传入时,hook里面是没办法去知道对应api的类型的,当然你做一个返回值传出来,就行了
import { ref } from 'vue'interface Base {
limit?: number
current?: number
}
interface A extends Base {
name: string
age: number
}
interface User {
id: string
name: string
address: string
age: number
}
declare function getList(params: A): Promise<{
data: User[]
}>
function useTable<P extends Base, T extends unknown>(
api: (params: P) => Promise<{
data: T[]
}>,
searchParams: P
) {
const list = ref<T[]>([])
api(searchParams)
.then(res => {
list.value = res.data
})
return list
}
const list = useTable(
getList,
{ age: 1, name: 'jack' }
)
以上是 table hooks下的入参类型如何定义ts? 的全部内容, 来源链接: utcz.com/p/933665.html