Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

Typescript对于第三方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一样的类型呢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

我的就很简单,这样倒是可以套一层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
}

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...