graphql-typed-document-node is a development tool for creating fully typed DocumentNode objects. It means that just by passing the GraphQL query/mutation/subscription/fragment to a supporting GraphQL client library, you'll get a fully type result object and variables object.
Configure your project to use this library (see How to use?).
You write your GraphQL operations (query / mutation / subscription / fragment) in any way your prefer (for example - in a .graphql file).
GraphQL Code Generator will generate a TypedDocumentNode for your operations (which is a bundle of pre-compiled DocumentNode with the operation result type and variables type).
Instead of using your .graphql file - import the generated TypedDocumentNode and use it with your GraphQL client framework.
You'll get automatic type inference, auto-complete and type checking based on your GraphQL operation.
Supported Libraries
Most libraries supports DocumentNode as the type of the query object, but that's not enough to use this library.
Our goal is to get built-in support in major libraries, in order
In order to extend the behavior, we are using patch-package library internally, to add support for TypedDocumentNode and add the support for type inference.
The following patches are currently supported:
Built-in support
@apollo/client (since 3.2.0, if you are using React Components (<Query>) you still need a patch)
Try to run codegen by using: yarn graphql-codegen, it should create the ./src/graphql-operations.ts file for you, with the generated TypedDocumentNode objects.
If you are using a library that doesn't support TypedDocumentNode yet, you can apply a patch, by doing:
Reinstall dependencies (using npm or yarn) - it will now patch the relevant libraries.
Now, after installing your projects' dependencies, it will make sure to patch all relevant packages and make it available for use with TypedDocumentNode.
Utils
The core package of typed-document-node exports 3 types only:
TypedDocumentNode - the base of this library.
ResultOf - a utils for extracting the result type from an existing TypeDocumentNode instance (ResultOf<typeof MyQueryDocument>)
VariablesOf - a utils for extracting the variables type from an existing TypeDocumentNode instance (VariablesOf<typeof MyQueryDocument>)
How can I support this in my library?
If you are a library maintainer, and you wish to have built-in TS support in your library, you can add support for TypedDocumentNode without having any breaking changes to your API.
Basically, in any place where you need to have typed access to the result type of an operation, or to a typed variables object, make sure to have generics for both types, and use TypeDocumentNode in your arguments, instead of DocumentNode. This will allow TypeScript to infer the types based on the object you are passing to it later.
请发表评论