Generate enum objects rather than types from graphql

I am trying to use enums as objects in my codebase based on the types generated from the graphql file.

worker.sdl.ts

  enum WorkerTypeEnum {
    EMPLOYEE
    CONTRACTOR
  }

Generated Type after yarn rw g types

export type WorkerTypeEnum =
  | 'CONTRACTOR'
  | 'EMPLOYEE'

codegen.yaml

config:
  enumsAsTypes: false
  futureProofEnums: true
  enumsAsConst: true

I want to be able to use these enums as objects in the code base and not just as types.

import { WorkerTypeEnum } from 'types/graphql'

if (person.Type === WorkerTypeEnum.Contractor)
  # do something
}

Hey @shortcut, others probably know more than me but I don’t think our codegen is set up to do what you want here, though it’s come up a few times so we hear you. We generate declaration files (.d.ts), whereas enums also involve generating JS code eventually I believe.

Hi @shortcut - there is also another approach and that’s to get the enum as data via graphql.

See https://github.com/redwoodjs/redwood-office-hours/tree/main/2022-10-05-enum-select-options

While this example was for select lists or radio options, it could be applied for other purposes

Or another idea would be to implement an isContractor field in your return type that can check the enum on the api side as a Prisma type.

Instead of getting the enum object from graphql, you can also import it from ‘@prisma/client’ if that works for your usecase.

Unfortunately the Prisma client isn’t available in the web side.so you cannot use it there to import types.

1 Like