You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置graphql-codegen以原始类型替代Scalar生成TypeScript类型?

问题:让graphql-codegen直接生成原始类型而非Scalars引用

使用graphql-codegen的typescript和typescript-operations插件生成TypeScript类型的体验出色,但默认生成的类型会采用Scalars['String']这类引用形式,而非直接的原始类型(如string),示例代码如下:

/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
  ID: string;
  String: string;
  Boolean: boolean;
  Int: number;
  Float: number;
};

export type Account = {
  __typename?: 'Account';
  created: Scalars['String'];
}

希望生成的代码直接使用原始类型,例如:

export type Account = {
  __typename?: 'Account';
  created: string; // 替代 Scalars['String']
}

已尝试编写自定义插件遍历对象属性修改类型,但过程繁琐,想了解是否有更简洁的实现方式?


解决方案

无需编写自定义插件,typescript插件本身提供了配置项可直接实现该需求:

  • 在你的codegen.yml(或对应格式的配置文件)中,为typescript插件添加scalars配置,将内置标量直接映射为原始类型,关键配置示例如下:
generates:
  ./src/generated/graphql.ts:
    plugins:
      - typescript
      - typescript-operations
    config:
      scalars:
        ID: string
        String: string
        Boolean: boolean
        Int: number
        Float: number
      noExport: true # 可选,设置为true会移除自动生成的Scalars类型定义
  • 配置说明:
    • scalars:显式指定每个GraphQL标量对应的TypeScript原始类型,插件会直接使用这些类型,不再通过Scalars映射引用。
    • noExport: true:如果不需要保留全局的Scalars类型定义,可以添加该配置,生成的代码中将完全移除Scalars相关内容。

这样配置后,生成的类型就会直接使用string、number等原始类型,无需额外修改。


内容的提问来源于stack exchange,提问作者judehall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:02:52