Skip to content

Commit

Permalink
Add MethodResponse utility type (#1831)
Browse files Browse the repository at this point in the history
* Add MethodResponse utility type

* Add type test for MethodResponse

* add cahngeset

* fix formatting
  • Loading branch information
SebastienGllmt authored Aug 12, 2024
1 parent 9c51678 commit 091e71a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/hip-years-invite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-fetch": patch
---

Add MethodResponse utility type to easily get the return type of an endpoint on a client
14 changes: 14 additions & 0 deletions packages/openapi-fetch/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,20 @@ export interface Client<Paths extends {}, Media extends MediaType = MediaType> {
eject(...middleware: Middleware[]): void;
}

export type ClientPathsWithMethod<
CreatedClient extends Client<any, any>,
Method extends HttpMethod,
> = CreatedClient extends Client<infer Paths, infer _Media> ? PathsWithMethod<Paths, Method> : never;

export type MethodResponse<
CreatedClient extends Client<any, any>,
Method extends HttpMethod,
Path extends ClientPathsWithMethod<CreatedClient, Method>,
Options = {},
> = CreatedClient extends Client<infer Paths extends { [key: string]: any }, infer Media extends MediaType>
? NonNullable<FetchResponse<Paths[Path][Method], Options, Media>["data"]>
: never;

export default function createClient<Paths extends {}, Media extends MediaType = MediaType>(
clientOptions?: ClientOptions,
): Client<Paths, Media>;
Expand Down
2 changes: 2 additions & 0 deletions packages/openapi-fetch/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { HttpResponse, type StrictResponse } from "msw";
import { afterAll, beforeAll, describe, expect, expectTypeOf, it } from "vitest";
import createClient, {
type MethodResponse,
type Middleware,
type MiddlewareCallbackParams,
type QuerySerializerOptions,
Expand Down Expand Up @@ -133,6 +134,7 @@ describe("client", () => {
created_at: number;
updated_at: number;
}>();
expectTypeOf(result.data).toEqualTypeOf<MethodResponse<typeof client, "get", "/mismatched-errors">>();
} else {
expectTypeOf(result.data).toBeUndefined();
expectTypeOf(result.error).extract<{ code: number }>().toEqualTypeOf<{ code: number; message: string }>();
Expand Down

0 comments on commit 091e71a

Please sign in to comment.