首页 > 解决方案 > 覆盖从 GraphQL Schema 生成的 Typescript 类型

问题描述

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

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

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

如您所见,GraphQL 默认标量类型(如 String、Boolean 等)将映射到等效的 Typescript 类型。自定义标量类型,如NodeDescription将获得 typescript type any

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

我的第一个想法是Scalars["NodeDescription"]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}>

这实际上有效,但类型的ast字段CodeResource仍然是 type any

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

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

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

标签: typescriptcode-generationtypescript-generics

解决方案


如果您使用graphql-code-generator 遇到相同的问题,我找到了一个特定的解决方案。有一个名为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

推荐阅读