Type Safety with GraphQL Fragments
What you'll learn: How GraphQL fragments generate reusable, type-safe data shapes that prevent over-fetching and keep your queries maintainable.
What Are GraphQL Fragments?
GraphQL fragments are reusable pieces of query logic that define which fields you want from a particular type. Think of them like "query components" — just as you build UI from reusable React components, you build queries from reusable fragments.
The Type Safety Problem Fragments Solve
Without fragments, you might write multiple queries that select the same fields from a User type. Each query generates its own TypeScript type, and those types can drift apart. You end up with inconsistent shapes across your codebase, making refactoring dangerous.
Fragments ensure that whenever you need "user profile data," you get exactly the same TypeScript type — no more, no less.
How GraphQL Codegen Creates Types from Fragments
When you use GraphQL Code Generator with fragments, it creates a dedicated TypeScript type for each fragment. That type precisely matches the fields you selected:
fragment UserProfile on User {
id
username
email
}
This generates a UserProfileFragment type that your components can import and use. Any query that spreads this fragment inherits that exact type automatically.
Preventing Over-Fetching with Type Precision
Because fragment types only include the fields you explicitly request, TypeScript won't let you access fields you didn't ask for. This compile-time enforcement prevents runtime errors where you assume data exists but never fetched it.
Composing Fragments for Complex Queries
Fragments compose naturally — you can spread one fragment inside another. GraphQL Codegen tracks these relationships and generates nested types that reflect your exact query structure. Your type safety follows your data requirements perfectly.
Key Takeaway: GraphQL fragments with codegen give you reusable, type-safe data shapes that stay synchronized between your queries and TypeScript code, eliminating inconsistencies and preventing access to unfetched fields.