如何缩小 graphQL codegen 自动生成的 Typescript 类型?
How to narrow Typescript Types autogenerated by graphQL codegen?
我得到一个从 AWS-Amplify GraphQL(我相信它使用 apollo-codegen)自动生成的 TypeScript 类型,如下所示:
export type GetNoteQuery = {
getNote: {
__typename: "Note",
id: string,
createdAt: string | null,
updatedAt: string | null,
title: boolean | null,
content: string | null,
} | null,
我想生成一个 "Note" 的基本类型,以用作 "base" 类型,以便在使用返回数据时在我的代码中使用。 IE。将笔记映射到 React 组件等
有没有办法缩小这种自动生成的类型,或者以某种方式扩展它,使其看起来像:
type Note = {
id: string,
createdAt: string | null,
updatedAt: string | null,
title: boolean | null,
content: string | null
}
您可以使用索引查询来获取 getNote
的类型以及 Exclude
以从 属性 类型中删除 null
。然后,您可以使用 Omit
删除多余的 属性。
export type GetNoteQuery = {
getNote: {
__typename: "Note",
id: string,
createdAt: string | null,
updatedAt: string | null,
title: boolean | null,
content: string | null,
} | null
}
type Note = Omit<Exclude<GetNoteQuery['getNote'], null>, '__typename'>
您还可以使用接口为类型获取更强的名称:
interface Note extends Omit<Exclude<GetNoteQuery['getNote'], null>, '__typename'> { }
这里是 GraphQL-Codegen 创建者。
关于决定生成这种 TS 代码的一些背景:
我们开始 typescript
作为一个插件来创建 GraphQL 模式的精确表示。
然后,typescript-operations
获取操作和片段(从模式中选择特定字段和数据)并生成代码,这些代码通过 typescript
插件从生成的类型中获取相同的字段和数据字段。
我们看到一些开发人员更喜欢更简洁的代码,因此您可以使用 preResolveTypes: true
来避免使用 Pick
,而只需就地使用原始类型。
您还可以使用 onlyOperationTypes: true
来告诉代码生成器避免生成不需要的类型。
我得到一个从 AWS-Amplify GraphQL(我相信它使用 apollo-codegen)自动生成的 TypeScript 类型,如下所示:
export type GetNoteQuery = {
getNote: {
__typename: "Note",
id: string,
createdAt: string | null,
updatedAt: string | null,
title: boolean | null,
content: string | null,
} | null,
我想生成一个 "Note" 的基本类型,以用作 "base" 类型,以便在使用返回数据时在我的代码中使用。 IE。将笔记映射到 React 组件等
有没有办法缩小这种自动生成的类型,或者以某种方式扩展它,使其看起来像:
type Note = {
id: string,
createdAt: string | null,
updatedAt: string | null,
title: boolean | null,
content: string | null
}
您可以使用索引查询来获取 getNote
的类型以及 Exclude
以从 属性 类型中删除 null
。然后,您可以使用 Omit
删除多余的 属性。
export type GetNoteQuery = {
getNote: {
__typename: "Note",
id: string,
createdAt: string | null,
updatedAt: string | null,
title: boolean | null,
content: string | null,
} | null
}
type Note = Omit<Exclude<GetNoteQuery['getNote'], null>, '__typename'>
您还可以使用接口为类型获取更强的名称:
interface Note extends Omit<Exclude<GetNoteQuery['getNote'], null>, '__typename'> { }
这里是 GraphQL-Codegen 创建者。
关于决定生成这种 TS 代码的一些背景:
我们开始 typescript
作为一个插件来创建 GraphQL 模式的精确表示。
然后,typescript-operations
获取操作和片段(从模式中选择特定字段和数据)并生成代码,这些代码通过 typescript
插件从生成的类型中获取相同的字段和数据字段。
我们看到一些开发人员更喜欢更简洁的代码,因此您可以使用 preResolveTypes: true
来避免使用 Pick
,而只需就地使用原始类型。
您还可以使用 onlyOperationTypes: true
来告诉代码生成器避免生成不需要的类型。