Skip to content

Add MethodResponse utility type #1831

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -190,6 +190,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 @@ -132,6 +133,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