What is @graphql-codegen/typed-document-node?
The @graphql-codegen/typed-document-node package is a plugin for the GraphQL Code Generator tool. It generates fully typed TypeScript documents from GraphQL operations and fragments. This enhances the development experience by providing type safety and autocompletion directly in the IDE, reducing the risk of runtime errors and improving code quality.
What are @graphql-codegen/typed-document-node's main functionalities?
Type-safe GraphQL operations
This feature allows developers to use GraphQL operations like queries, mutations, and subscriptions with complete type safety. The code sample demonstrates how to use a typed query with Apollo Client, ensuring that both the variables and the returned data conform to the expected types.
import { useQuery } from '@apollo/client';
import { MyQuery, MyQueryVariables } from './generated/graphql';
const { data, loading, error } = useQuery<MyQuery, MyQueryVariables>(MY_QUERY, { variables: { id: '1' } });
Integration with GraphQL fragments
This feature supports the use of GraphQL fragments, generating TypeScript types that can be extended or integrated into larger data structures. The code sample shows how to extend a generated fragment type with additional fields, leveraging TypeScript's type extension capabilities.
import { MyFragment } from './generated/graphql';
interface ExtendedType extends MyFragment {
additionalField: string;
}
const extendedData: ExtendedType = { ...fragmentData, additionalField: 'extra' };
Other packages similar to @graphql-codegen/typed-document-node
@graphql-codegen/typescript
This package is part of the same GraphQL Code Generator ecosystem. It focuses on generating TypeScript types for GraphQL schema. Compared to @graphql-codegen/typed-document-node, it does not directly generate typed document nodes but rather the types that can be used to manually create typed documents.
@apollo/client
While primarily a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL, Apollo Client can be configured to use TypeScript for type safety. It differs from @graphql-codegen/typed-document-node in that it's an all-in-one solution that includes client-side data fetching and caching, rather than just a code generation tool.