覆盖从 GraphQL Schema 生成的 Typescript 类型

Override from GraphQL Schema generated Typescript types

我正在使用 graphql-code-generator 从我的 GraphQL 架构中生成打字稿类型。 在 GraphQL 中,您可以创建自定义标量类型,它将生成以下类型: /graphql.ts

export type Scalars = {
  String: string;
  Boolean: boolean;
  NodeDescription: any;
};

export type CodeResource = {
  ast: Scalars["NodeDescription"];
};

如您所见,GraphQL 默认标量类型(如字符串、布尔值等)将映射到等效的 Typescript 类型。 NodeDescription 等自定义标量类型将获得打字稿类型 any.

在我的 Angular 客户端中已经有一个 NodeDescription 类型(在 ../app/shared/syntaxtree 中),我想使用它来代替生成的 any 类型。 有没有办法覆盖 Scalars 类型中的 NodeDescription 字段? 所以最后我希望生成的 CodeResource 类型的 ast 字段具有类型 NodeDescription 而不是 any.

我的第一个想法是用 NodeDescription 覆盖 Scalars["NodeDescription"] 类型。所以我尝试将所有类型导入一个新文件并覆盖它们,例如: /types.ts

import {Scalars} from "./graphql";
import {NodeDescription} from "../app/shared/syntaxtree";
type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
type Scalar = Overwrite<Scalars, {NodeDescription: NodeDescription}>

这确实有效,但是 CodeResource 类型的 ast 字段仍然是 any 类型。

另一个想法是使用 bash 脚本和经过深思熟虑的 sed 命令,这样生成的文件将被编辑为:

import {NodeDescription} from "../app/shared/syntaxtree";
export type Scalars = {
  String: string;
  Boolean: boolean;
  NodeDescription: NodeDescription;
};

然而,在我实施该方法之前,我想知道是否有一种智能打字稿方法来覆盖生成的类型。感谢您的帮助。

如果您在使用 graphql-code-generator. There is a plugin called add 时遇到同样的问题,我找到了一个具体的解决方案。 因此,在 codegen.yml 中,您可以添加导入并处理自定义标量类型。我的 codegen.yml 现在看起来像这样:

overwrite: true
schema: "../schema/graphql/schema.json"
documents: "../schema/graphql/**/*.graphql"
generates:
  src/generated/graphql.ts:
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-apollo-angular"
      - add:
          content: 'import { NodeDescription } from "../app/shared/syntaxtree";'
    config:
      enumsAsTypes: true
      scalars:
        NodeDescription: NodeDescription
        ISO8601DateTime: string