Skip to content
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

feat: allow embedding the operation result type #148

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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/empty-lions-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@graphql-typed-document-node/core": minor
---

allow embedding the operation result type
28 changes: 21 additions & 7 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import type { DocumentNode } from "graphql";

export type OperationResultType = "stream" | "single";

export interface TypedDocumentNode<
Result = { [key: string]: any },
Variables = { [key: string]: any }
Variables = { [key: string]: any },
ResultType extends OperationResultType = any
> extends DocumentNode {
/**
* This type is used to ensure that the variables you pass in to the query are assignable to Variables
* and that the Result is assignable to whatever you pass your result to. The method is never actually
* implemented, but the type is valid because we list it as optional
*/
__apiType?: (variables: Variables) => Result;
__apiType?: (variables: Variables, resultType: ResultType) => Result;
}

/**
Expand All @@ -18,10 +21,7 @@ export interface TypedDocumentNode<
* const myQuery = { ... }; // TypedDocumentNode<R, V>
* type ResultType = ResultOf<typeof myQuery>; // Now it's R
*/
export type ResultOf<T> = T extends TypedDocumentNode<
infer ResultType,
infer VariablesType
>
export type ResultOf<T> = T extends TypedDocumentNode<infer ResultType, any>
? ResultType
: never;

Expand All @@ -32,8 +32,22 @@ export type ResultOf<T> = T extends TypedDocumentNode<
* type VariablesType = VariablesOf<typeof myQuery>; // Now it's V
*/
export type VariablesOf<T> = T extends TypedDocumentNode<
infer ResultType,
any,
infer VariablesType
>
? VariablesType
: never;

/**
* Helper for extracting a TypeScript type for operation type from a TypedDocumentNode.
* @example
* const myQuery = { ... }; // TypedDocumentNode<R, V, O>
* type OperationType = VariablesOf<typeof myQuery>; // Now it's O
*/
export type OperationTypeOf<T> = T extends TypedDocumentNode<
any,
any,
infer OperationType
>
? OperationType
: never;