ts封装第三方API如何保持类型一致?
我需要使用ahooks
(阿里巴巴的react hook库)的useRequest
,然后根据我的需求,我想要封装一层通用处理,也就是包裹成一个自定义的hook。
ahooks的useRequest
是有多个类型声明的,如下代码所示。
declare function useRequest<R = any, P extends any[] = any, U = any, UU extends U = any>(service: CombineService<R, P>, options: OptionsWithFormat<R, P, U, UU>): BaseResult<U, P>;declare function useRequest<R = any, P extends any[] = any>(service: CombineService<R, P>, options?: BaseOptions<R, P>): BaseResult<R, P>;
declare function useRequest<R extends LoadMoreFormatReturn, RR>(service: CombineService<RR, LoadMoreParams<R>>, options: LoadMoreOptionsWithFormat<R, RR>): LoadMoreResult<R>;
declare function useRequest<R extends LoadMoreFormatReturn, RR extends R>(service: CombineService<R, LoadMoreParams<R>>, options: LoadMoreOptions<RR>): LoadMoreResult<R>;
declare function useRequest<R = any, Item = any, U extends Item = any>(service: CombineService<R, PaginatedParams>, options: PaginatedOptionsWithFormat<R, Item, U>): PaginatedResult<Item>;
declare function useRequest<R = any, Item = any, U extends Item = any>(service: CombineService<PaginatedFormatReturn<Item>, PaginatedParams>, options: BasePaginatedOptions<U>): PaginatedResult<Item>;
我自定义的hook,只是为了处理通用错误和通用请求的。。。其他传参和返回也应该和useRequest
保持一致性。
我该如何给自定义的hook声明和useRequest
一样的类型呢
回答
我的就很简单,这样倒是可以套一层hook
import useRequest from "@umijs/use-request"import { BaseOptions } from "@umijs/use-request/lib/types"
export function useNetworkTask<Result, Data, P extends any[] = any>(url: string, data: Data, options?: BaseOptions<Result, P>) {
const result = useRequest<Result>(url, {
...options
})
return result
}
以上是 ts封装第三方API如何保持类型一致? 的全部内容, 来源链接: utcz.com/a/44949.html