繁体   English   中英

覆盖 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 默认标量类型(如 String、Boolean 等)将映射到等效的 Typescript 类型上。 NodeDescription这样的自定义标量类型将获得NodeDescription类型any

在我的 Angular 客户端中,已经有一个NodeDescription类型(在 ../app/shared/syntaxtree 中),我想使用它而不是生成的any类型。 有没有办法覆盖标量类型中的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字段仍然是 type any

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

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

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

如果您使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM