interface paths {
"/url1": {
get: operations["editUsingPUT"];
};
"/url2": {
get: operations["listUsingGET"];
};
"/url3": {
post: operations["listUsingGET"];
};
}
interface operations {
editUsingPUT: {
requestBody?: {
content: {
a: number;
};
};
responses: {
200: {
content: {
};
};
};
};
addUsingPOST: {
requestBody?: {
content: {
b: number;
};
};
responses: {
200: {
content: {
"*/*": {
[key: string]: Record<string, never>;
};
};
};
};
};
listUsingGET: {
parameters: {
query: {
updateTime?: string;
};
};
}
}
export type HttpMethod = | "get" | "post"| "trace";
export type PathsWithMethod<
Paths extends {},
PathnameMethod extends HttpMethod,
> = {
[Pathname in keyof Paths]: Paths[Pathname] extends {
[K in PathnameMethod]: any;
}
? Pathname
: never;
}[keyof Paths];
export type FilterKeys<Obj, Matchers> = {
[K in keyof Obj]: K extends Matchers ? Obj[K] : never;
}[keyof Obj];
export type ResponseObjectMap<T> = T extends { responses: any }
? T["responses"]
: unknown;
export type MediaType = `${string}/${string}`;
export type OkStatus = 200 | 201 | 202 | 203 | 204 | 206 | 207 | "2XX";
export type ResponseContent<T> = T extends { content: any }
? T["content"]
: unknown;
export type SuccessResponse<T> = ResponseContent<FilterKeys<T, OkStatus>>;
export type FetchResponse<T> =
| {
data: FilterKeys<SuccessResponse<ResponseObjectMap<T>>, MediaType>;
error?: never;
response: Response;
};
function createClient<Paths extends {}>(
): {
GET<P extends PathsWithMethod<Paths, "get">>(
url: P
): Promise<
FetchResponse<
"get" extends infer T
? T extends "get"
? T extends keyof Paths[P]
? Paths[P][T]
: unknown
: never
: never
>
>;
}
function createClient() {
return {
async GET(url, init) {
return new Promise((resolve, reject) => {})
}
}
}
const client = createClient<paths>();
const data = await client.GET("/url1")
// 如何实现对client的包装 而且保留client 的ts提示
// 网上的方法1 但是返回值无法实现
export type Client = typeof client;
export type ApiCall = (client: Client) => Promise<FetchResponse<T>>;
export function useApi() {
return async function (apiCall: ApiCall) {
const response = await apiCall(client);
return response.data;
};
}
如何实现对client的包装 且保留client的ts提示,网上找的这个方法对于 Promise的返回值没有提示
希望包装client后能有代码提示
原项目地址
https://github.com/drwpow/openapi-typescript/issues/1122#issuecomment-1790660170
github 地址
https://github.com/drwpow/openapi-typescript/issues/1122#issuecomment-1790660170