如何缩小由graphQL codegen自动生成的Typescript类型?

Ste*_*ano 6 typescript graphql aws-appsync aws-amplify

我得到了一个从 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,
Run Code Online (Sandbox Code Playgroud)

我想生成一个“Note”的基本类型,用作“基本”类型,以便在使用返回的数据时在我的代码中使用。即将笔记映射到 React 组件等。

有没有办法缩小这种自动生成的类型,或者以某种方式扩展它,让它看起来像:

export type GetNoteQuery = {
  getNote:  {
    __typename: "Note",
    id: string,
    createdAt: string | null,
    updatedAt: string | null,
    title: boolean | null,
    content: string | null,
  } | null,
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 2

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'>

Run Code Online (Sandbox Code Playgroud)

您还可以使用接口来为该类型获取更强的名称:


interface Note extends Omit<Exclude<GetNoteQuery['getNote'], null>, '__typename'> { }


Run Code Online (Sandbox Code Playgroud)

  • @StephenA.Lizcano 类型别名在错误和工具提示中得到扩展,因此您可能会看到类似“Pick&lt;Exclude&lt;...”的内容,而不是“Note”。接口名称始终被保留。 (2认同)