typescriptgraphqlgraphql-codegen

Adding a custom type to codegen.yml


My GraphQL schema uses a type called PointScalar, which in Typescript would be defined as

export type PointScalar = {
  coordinates: [number, number]
}

Without any modification, codegen declares PointScalar fields as Scalars['PointScalar'], which in turn is any.

I can add this to GraphQL:

config:
  scalars:
    PointScalar: PointScalar

which causes codegen to declare PointScalar as PointScalar, which is great ... but it doesn’t know what a PointScalar is.

How do I get codegen to add an import file or a type statement to the generated Typescript?


Solution

  • You're almost there.

    // Name this file as (or anything you prefer): scalar-types.ts
    // Place it relative to your codegen-generated types file.
    
    export type PointScalar = {
      coordinates: [number, number]
    }
    

    Modify your code to point a file instead. #-points a exported type in the file.

    // file: codegen.yml
    schema: "my-graphql-schema.graphql"
    generates:
      ./index.ts:
    config:
       scalars:
          PointScalar: ./scalar-types#PointScalar
    

    Run Codegen and the following import is at the top of your output.

    import { PointScalar } from './scalar-types';