Skip to content

Commit 091e71a

Browse files
Add MethodResponse utility type (#1831)
* Add MethodResponse utility type * Add type test for MethodResponse * add cahngeset * fix formatting
1 parent 9c51678 commit 091e71a

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

.changeset/hip-years-invite.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"openapi-fetch": patch
3+
---
4+
5+
Add MethodResponse utility type to easily get the return type of an endpoint on a client

packages/openapi-fetch/src/index.d.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,20 @@ export interface Client<Paths extends {}, Media extends MediaType = MediaType> {
202202
eject(...middleware: Middleware[]): void;
203203
}
204204

205+
export type ClientPathsWithMethod<
206+
CreatedClient extends Client<any, any>,
207+
Method extends HttpMethod,
208+
> = CreatedClient extends Client<infer Paths, infer _Media> ? PathsWithMethod<Paths, Method> : never;
209+
210+
export type MethodResponse<
211+
CreatedClient extends Client<any, any>,
212+
Method extends HttpMethod,
213+
Path extends ClientPathsWithMethod<CreatedClient, Method>,
214+
Options = {},
215+
> = CreatedClient extends Client<infer Paths extends { [key: string]: any }, infer Media extends MediaType>
216+
? NonNullable<FetchResponse<Paths[Path][Method], Options, Media>["data"]>
217+
: never;
218+
205219
export default function createClient<Paths extends {}, Media extends MediaType = MediaType>(
206220
clientOptions?: ClientOptions,
207221
): Client<Paths, Media>;

packages/openapi-fetch/test/index.test.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { HttpResponse, type StrictResponse } from "msw";
22
import { afterAll, beforeAll, describe, expect, expectTypeOf, it } from "vitest";
33
import createClient, {
4+
type MethodResponse,
45
type Middleware,
56
type MiddlewareCallbackParams,
67
type QuerySerializerOptions,
@@ -133,6 +134,7 @@ describe("client", () => {
133134
created_at: number;
134135
updated_at: number;
135136
}>();
137+
expectTypeOf(result.data).toEqualTypeOf<MethodResponse<typeof client, "get", "/mismatched-errors">>();
136138
} else {
137139
expectTypeOf(result.data).toBeUndefined();
138140
expectTypeOf(result.error).extract<{ code: number }>().toEqualTypeOf<{ code: number; message: string }>();

0 commit comments

Comments
 (0)