diff --git a/.changeset/empty-lions-behave.md b/.changeset/empty-lions-behave.md new file mode 100644 index 0000000..fc4ccef --- /dev/null +++ b/.changeset/empty-lions-behave.md @@ -0,0 +1,5 @@ +--- +"@graphql-typed-document-node/core": minor +--- + +allow embedding the operation result type diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7a0c1b5..2a2b928 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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; } /** @@ -18,10 +21,7 @@ export interface TypedDocumentNode< * const myQuery = { ... }; // TypedDocumentNode * type ResultType = ResultOf; // Now it's R */ -export type ResultOf = T extends TypedDocumentNode< - infer ResultType, - infer VariablesType -> +export type ResultOf = T extends TypedDocumentNode ? ResultType : never; @@ -32,8 +32,22 @@ export type ResultOf = T extends TypedDocumentNode< * type VariablesType = VariablesOf; // Now it's V */ export type VariablesOf = 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 + * type OperationType = VariablesOf; // Now it's O + */ +export type OperationTypeOf = T extends TypedDocumentNode< + any, + any, + infer OperationType +> + ? OperationType + : never;