typescript - 覆盖从 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;
};
但是,在我实现该方法之前,我想知道是否有一种智能打字稿方式来覆盖生成的类型。感谢帮助。
解决方案
如果您使用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
推荐阅读
- python - 输入到 LSTM 的时间序列
- function - 基本功能查询
- python - Tkinter - 如何通过单击矩形获取标签名称
- node.js - 处理异步流:在nodejs中过滤日期后读取和写入多个csv文件
- python - ortools中修改公交调度问题
- python - 如何在熊猫数据框中找到错误值?
- javascript - 如何在 javascript 循环中调用 json 列
- javascript - Vue:数据未绑定到道具,因此未使用 vue-D3-charts 渲染 BarChart
- python - 尽管在 IDE/IDLE 中工作正常,但在使用控制台时没有这样的文件或目录
- visual-studio-code - 如何从 VSCode 的活动栏中永久隐藏/删除扩展视图 - OSS