Closed10

graphql-codegen で enum を使いたくない...

nbstshnbstsh

graphql-codegen で SDL から ts の型定義を自動生成する際に、graphql の enum が ts の enum として生成されてしまう。ts で enum は使いたくないので、opt out する方法を調べる。

現状

enum Role {
  ADMIN
  EDITOR
  VIEWER
}

これが、こうなる↓

export enum Role {
  Admin = 'ADMIN',
  Editor = 'EDITOR',
  Viewer = 'VIEWER'
}

理想

理想としては、こうなってほしい↓

export const ROLE  = {
  Admin: 'ADMIN',
  Editor: 'EDITOR',
  Viewer: 'VIEWER'
} as const;

export type Role = typeof ROLE[keyof typeof ROLE];
nbstshnbstsh

constEnums

type: boolean default: false

Will prefix every generated enum with const, you can read more about const enums here: > https://www.typescriptlang.org/docs/handbook/enums.html.

enum を const 付きで生成。

export const enum Role {
  Admin = 'ADMIN',
  Editor = 'EDITOR',
  Viewer = 'VIEWER'
};
nbstshnbstsh

const enum とは

Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation. Const enum members are inlined at use sites. This is possible since const enums cannot have computed members.

compile 時に取り除かれ、inline で置換されるらしい

nbstshnbstsh

enumsAsTypes

type: boolean default: false

Generates enum as TypeScript type instead of enum. Useful if you wish to generate .d.ts declaration file instead of .ts

enum の代わりに type を生成

export type Role =
  | 'ADMIN'
  | 'EDITOR'
  | 'VIEWER';
nbstshnbstsh

enumsAsConst

type: boolean default: false

Generates enum as TypeScript const assertions instead of enum. This can even be used to enable enum-like patterns in plain JavaScript code if you choose not to use TypeScript’s enum construct.

export const Role = {
  Admin: 'ADMIN',
  Editor: 'EDITOR',
  Viewer: 'VIEWER'
} as const;

export type Role = typeof Role[keyof typeof Role];
nbstshnbstsh

まとめ

enumsAsConst を利用すればOK

codege.yml
generates:
  path/to/file.ts:
    plugins:
      - typescript
    config:
      enumsAsConst: true
このスクラップは2022/09/11にクローズされました