Skip to content

pachuka/-graphql-codegen-typed-document-node-fragment-namespace-bug

Repository files navigation

Typed Document Node Fragment Namespacing Bug - Reproducible Example

This repository demonstrates the bug in @graphql-codegen/typed-document-node@6.1.0+ where fragment types are incorrectly namespaced with Types. prefix when using the import-types preset.

The Issue

When using typed-document-node@6.1.0+ with the import-types preset, the generated code incorrectly adds a Types. prefix to all DocumentNode result types, including fragments. This causes TypeScript compilation errors because:

  1. Operation types come from the external Types namespace (correct)
  2. Fragment types are generated locally and should NOT be prefixed (but they are)

Expected Behavior (v6.0.2)

{ ...UserFragment } as unknown as DocumentNode<UserFragment, unknown>

Buggy Behavior (v6.1.0+)

{ ...UserFragment } as unknown as DocumentNode<Types.UserFragment, unknown>
// ❌ Error: Types namespace has no exported member 'UserFragment'

Root Cause

In PR #10456 (commit 655b91d), the typed-document-node plugin added the importOperationTypesFrom feature. The implementation indiscriminately applies the Types. prefix to ALL non-unknown result types without distinguishing between:

  • Operations (should be prefixed - they come from external Types namespace)
  • Fragments (should NOT be prefixed - they're generated locally)

Source: visitor.ts lines 101-103:

const resultImportPrefix = shouldUseImportPrefix && resultType !== 'unknown' ? 'Types.' : '';

Reproduction Steps

  1. Install dependencies:

    npm install
  2. Generate code:

    npm run codegen
  3. Attempt to compile:

    npm run build

Expected result: TypeScript compilation fails with errors like:

error TS2705: Namespace 'Types' has no exported member 'UserProfileFragment'
error TS2705: Namespace 'Types' has no exported member 'UserFragment'

Files

  • schema.graphql - Sample GraphQL schema
  • operations.graphql - Sample queries with fragments
  • codegen.ts - Code generation configuration
  • tsconfig.json - TypeScript configuration

Verification

After running codegen, examine the generated generated.ts file. You'll see fragment references like:

// WRONG - This is the bug
} as unknown as DocumentNode<Types.UserFragment, unknown>

This should be:

// CORRECT
} as unknown as DocumentNode<UserFragment, unknown>

About

Reproducible example of typed-document-node v6.1.0+ fragment namespacing bug

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages