Closed2

graphql codegen typescript 型エラー 修正

naokinaoki

問題

export type Scalars = {
  ID: string;
  String: string;
  Boolean: boolean;
  Int: number;
  Float: number;
  /** An ISO 8601-encoded datetime */
  ISO8601DateTime: any;   
};

ISO8601DateTimeanyで生成されてしまう部分が問題部分で型エラーに引っ掛かる

Unexpected any. Specify a different type  @typescript-eslint/no-explicit-any
naokinaoki

解決

codegenにはcustom scalarというものがあり、任意の型を指定することができるためISO8601DateTimeanyではなく別の型に変換すれば良い

apollo clientでは日付などのデータ取得はstring型を利用しているので以下のように設定ファイルを修正

codegen.yml
overwrite: true
schema: 'http://localhost:3001/graphql'
documents: 'src/**/*.graphql'
generates:
  src/graphql/graphql.tsx:
    plugins:
      - 'typescript'
      - 'typescript-operations'
      - 'typescript-react-apollo'
    # 以下を追加
    config:
      scalars:
        ISO8601DateTime: string

修正後のに生成された型

export type Scalars = {
  ID: string;
  String: string;
  Boolean: boolean;
  Int: number;
  Float: number;
  /** An ISO 8601-encoded datetime */
  ISO8601DateTime: string;
};

この記事で解決方法が解説されている。
https://www.wantedly.com/companies/wantedly/post_articles/387161

このスクラップは2022/05/23にクローズされました