Typescript constraint on query shape?

Hi, apologies if this has already been asked. Does anyone know of a way to leverage Typescript to constrain the shape/selection set of a query? Say you’re writing a function that receives QueryOptions as an argument, and the function executes the query specified by QueryOptions.query.

Let’s say the function is expecting a query with this shape:

query GetFoos ( $after: String, $first: Int ) {
  foos( first: $first, after: $after ) {
    pageInfo {
      endCursor
      hasNextPage
    }
    edges {
      cursor
      node {
        ...fields on node
      }
    }
  }
}

Now suppose we pass the function a query that is missing pageInfo in the selection set, or that aliases edges. Is there any way to have Typescript catch this, or would you have to provide your own validation of the query DocumentNode?

Thanks!

Hi,
not sure how others are doing it but I generate my typing using this:

My dev dependencies:

"@graphql-codegen/cli": "2.6.2",
"@graphql-codegen/typescript-resolvers": "2.6.4",
"@graphql-codegen/typescript-document-nodes": "2.2.11",
"@graphql-codegen/typescript": "2.4.11",
"@graphql-codegen/typescript-mongodb": "2.3.9",
"@graphql-codegen/introspection": "2.1.1"

Then you need config, my is simply called codegen.yml

overwrite: true
schema: "http://localhost:4000"
documents: null
generates:
  src/generated/graphql.ts:
    plugins:
      - "typescript"
      - "typescript-resolvers"
      - "typescript-mongodb"
      - "typescript-document-nodes"
  ./graphql.schema.json:
    plugins:
      - "introspection"

Using this config, generated code will be placed into src/generated and graphql.schema.json is in main directory.

Then you need script in package.json

"codegen": "graphql-codegen --config codegen.yml"

That’s it. You need to make sure that graphql server is responding correctly on http://localhost:4000
Then run the script. It will call the server, pull out config and generate typings for you. You will get types for your data, resolvers, everything.