Skip to content

Type error when graphql.query infers type arguments from TypedDocumentNode #2023

@aaronadamsCA

Description

@aaronadamsCA

Prerequisites

Environment check

  • I'm using the latest msw version
  • I'm using Node.js version 18 or higher

Browsers

No response

Reproduction repository

https://stackblitz.com/edit/msw-response-type-mismatch?file=index.ts

Reproduction steps

npm dev

Current behavior

When graphql.query infers its type arguments from a TypedDocumentNode argument, literal types in response bodies are widened by TypeScript, causing an error.

export const handler = graphql.query(MyQuery, () =>
  HttpResponse.json({ data: { parent: { foo: "BAR" } } }),
  // Type 'string' is not assignable to type '"BAR"'.
);

If you pass explicit type arguments, there is no longer an error, even though the explicit type arguments appear to be identical to the inferred type arguments.

export const handler = graphql.query<MyResult, MyVariables>(MyQuery, () =>
  HttpResponse.json({ data: { parent: { foo: "BAR" } } }),
  // No error
);

You can also work around this using const assertions, which is likely the best workaround for now.

export const handler = graphql.query(MyQuery, () =>
  HttpResponse.json({ data: { parent: { foo: "BAR" } } } as const),
  // No error
);

Expected behavior

I would expect TypeScript to evaluate identical function calls identically, regardless of whether the type arguments are passed explicitly or by inference.

Honestly, this feels more like a TypeScript issue than an MSW issue; still, maybe there's a way to resolve it at the library level, even if it just ends up being a documentation thing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingneeds:triageIssues that have not been investigated yet.scope:browserRelated to MSW running in a browser

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions