Generics Support
Go generics allow you to write reusable, type-safe code. GQLSchemaGen understands generic types and automatically expands them in your GraphQL schema, making it easy to use generic patterns like Response[T], Paginated[T], or Result[T, E] in your API.
How It Works
When you use a generic type in an annotated struct, GQLSchemaGen:
- Detects the generic instantiation (e.g.,
Response[*User]) - Substitutes type parameters with concrete types
- Expands embedded generic structs inline
- Generates proper GraphQL types with resolved field types
Basic Example
Generated GraphQL:
The generic Response[T] is expanded inline, and T is replaced with User.
Multiple Type Parameters
Generics with multiple type parameters are fully supported:
Generated:
Nested Generic Types
Generics can be nested and combined:
Generated:
Notice how Edge[*Product] becomes ProductConnectionEdge - GQLSchemaGen generates unique type names for generic instantiations.
Auto-Generation with Generics
Auto-generation works seamlessly with generics:
Both UserResponse and User are generated automatically.
Generic Type Naming
When GQLSchemaGen instantiates a generic type, it generates a unique name:
Pattern: {ParentType}{GenericType}{Index}
Examples:
Response[*User]embedded inUserResponse→ Fields expanded inline inUserResponseEdge[*Product]in slice →ProductConnectionEdgePair[*Key, *Value]→TypePair(where Type is the parent)
This ensures each generic instantiation gets a unique, conflict-free type name.
Unresolved Type Parameters
If a generic type parameter cannot be resolved (e.g., standalone Result[T]), you can configure a fallback:
Options:
""(empty) - Keep as-is, may cause out-of-scope warnings"JSON"- Use JSON scalar"Any"- Use Any scalar- Custom scalar name
Combining Generics with Annotations
You can use generic types alongside normal annotations:
Generated:
Generic Constraints
Go generic constraints are respected:
Generated:
Best Practices
- Define generic types once: Reuse across multiple concrete types
- Use meaningful type parameters:
Tfor data,Efor errors,K/Vfor key/value - Annotate concrete types: Put
@gqlTypeon the concrete instantiation, not the generic definition - Leverage auto-generation: Let GQLSchemaGen discover and generate referenced types
- Set unresolved fallback: Configure
unresolved_generic_typeto handle edge cases
Common Patterns
Response Wrapper
Paginated Results
Result Type (Either Pattern)
Limitations
- Generic definitions are not generated: Only concrete instantiations appear in the schema
- Type parameter inference: GQLSchemaGen uses actual type arguments, not inferred types
- Constraint checking: GraphQL schema doesn't enforce Go generic constraints
Once you've defined your generic types, run:
$ gqlschemagen generateto generate GraphQL schemas with fully expanded generic types.