From 6e7ec2871f5f82fbf228b803df565286b1d4dbfc Mon Sep 17 00:00:00 2001 From: Graeme Coupar Date: Sun, 30 Jan 2022 11:19:55 +0000 Subject: [PATCH] fix: allow variables inference in GraphQLRequest (#1081) * fix: allow variables inference in GraphQLRequest I noticed that the return type of a `graphql.query...` call is `GraphQLHandler>` - it's not propagating the variables generic parameter into the return type. I assume this wasn't intentional. This change annotates the constructor of the `GraphQLHandler` class with the correct generic parameters, so the return type should now be `GraphQLHandler>`. * test(graphql): add variables inference typing test Co-authored-by: Artem Zakharchenko --- src/graphql.ts | 14 ++++++++++++-- test/typings/graphql.test-d.ts | 26 +++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/graphql.ts b/src/graphql.ts index 9333e13f7..c01b8f454 100644 --- a/src/graphql.ts +++ b/src/graphql.ts @@ -36,7 +36,12 @@ function createScopedGraphQLHandler( GraphQLContext >, ) => { - return new GraphQLHandler(operationType, operationName, url, resolver) + return new GraphQLHandler>( + operationType, + operationName, + url, + resolver, + ) } } @@ -50,7 +55,12 @@ function createGraphQLOperationHandler(url: Path) { GraphQLContext >, ) => { - return new GraphQLHandler('all', new RegExp('.*'), url, resolver) + return new GraphQLHandler>( + 'all', + new RegExp('.*'), + url, + resolver, + ) } } diff --git a/test/typings/graphql.test-d.ts b/test/typings/graphql.test-d.ts index 3ec3564fa..93685fae7 100644 --- a/test/typings/graphql.test-d.ts +++ b/test/typings/graphql.test-d.ts @@ -1,5 +1,11 @@ import { parse } from 'graphql' -import { graphql } from 'msw' +import { + MockedRequest, + GraphQLRequest, + graphql, + GraphQLHandler, + GraphQLVariables, +} from 'msw' graphql.query<{ key: string }>('', (req, res, ctx) => { return res( @@ -109,3 +115,21 @@ graphql.mutation(createUser, (req, res, ctx) => }), ), ) + +// GraphQL request variables must be inferrable +// via the variables generic. +function extractVariables( + _handler: GraphQLHandler>, +): MockedRequest> { + return null as any +} +const handlerWithVariables = graphql.query<{ data: unknown }, { id: string }>( + 'GetUser', + () => void 0, +) +const handler = extractVariables(handlerWithVariables) + +handler.body.variables.id + +// @ts-expect-error Property "foo" is not defined on the variables generic. +handler.body.variables.foo