Graphql-code-generator: export enum as string type

Created on 11 Mar 2020  路  9Comments  路  Source: dotansimha/graphql-code-generator

I have an enum

enum Role {
  USER
  ADMIN
}

currently, it is generating as

export enum Role {
  USER = 'USER'
  ADMIN = 'ADMIN'
}

but I would like to get it as:

export type Role = 'USER' | 'ADMIN'
waiting-for-answer

Most helpful comment

@dotansimha maybe we should throw an error (or at least a warning) when we parse un unknown option?

All 9 comments

You're looking for the enumsAsTypes option, see https://graphql-code-generator.com/docs/plugins/typescript

it's still generating in this format:

export enum Role {
  USER = 'USER'
  ADMIN = 'ADMIN'
}

i tried both plugin level and global level

@suhailbinnisar enumsAsTypes should work. Can you please share you configuration? Which version do you use?

Versions:
Typescript: 4.39.2
@graphql-codegen/cli: 1.6.1
@graphql-codegen/typescrip: 1.6.1
@graphql-codegen/typescript-operations: 1.8.2
@graphql-codegen/typescript-react-apollo: 1.8.2
@graphql-codegen/typescript-resolvers: 1.13.0

My codegen.yml

schema: http://localhost:4000/

config:
  scalars:
    DateTime: Date
    JSON: { [key: string]: any }
  skipTypename: true
  nonOptionalTypename: true
  namingConvention:
    typeNames: change-case#pascalCase
    enumValues: change-case#upperCase

overwrite: true
documents: "./xsomepath/graphql/**/*.ts"

generates:
  ./somepath/index.d.ts:
    plugins:
      - typescript
   # **particularly this guy**
   # **START**
  ./somepath2/resolvers-types.ts:
    plugins:
      - typescript
      - typescript-resolvers
    config:
      enumAsType: true
      contextType: interfaces/common#IResolverContext
   # **END**
  ./somepath3/Components.tsx:
    plugins:
      - typescript-operations
      - typescript-react-apollo
    config:
      withHooks: true
      withComponents: false
  ./somepath4/index.d.ts:
    plugins:
      - typescript

partial screenshot of generated file

Screenshot from 2020-03-12 15-40-24

done!

It's enumsAsTypes with the final s

@darkbasic oh man, thanks a lot, I should really start copy-pasting even small things word-to-word from docs, thanks a lot

@dotansimha maybe we should throw an error (or at least a warning) when we parse un unknown option?

@darkbasic we will create soon JSON schema validation for the YAML files, I think it will help to avoid those issues :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iamdanthedev picture iamdanthedev  路  3Comments

mdaouas picture mdaouas  路  3Comments

NickClark picture NickClark  路  3Comments

quolpr picture quolpr  路  3Comments

fvisticot picture fvisticot  路  3Comments