【问题标题】:How to narrow Typescript Types autogenerated by graphQL codegen?如何缩小由 graphQL codegen 自动生成的 Typescript 类型?
【发布时间】:2020-02-29 04:07:33
【问题描述】:

我得到了一个从 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”作为“基本”类型在我的代码中使用。 IE。将注释映射到 React 组件等。

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

type Note = {
    id: string,
    createdAt: string | null,
    updatedAt: string | null,
    title: boolean | null,
    content: string | null
}

【问题讨论】:

    标签: typescript graphql aws-amplify aws-appsync


    【解决方案1】:

    您可以使用索引查询来获取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'> { }
    
    
    

    【讨论】:

    • 谢谢!使用接口“为类型获取更强的名称”是什么意思?
    • @StephenA.Lizcano 类型别名在错误和工具提示中得到扩展,因此您可能会看到类似 Pick&lt;Exclude&lt;.... 而不是 Note 的内容。接口名称始终保留。
    【解决方案2】:

    GraphQL-Codegen 创建者在这里。

    关于生成这种 TS 代码的决定的一些背景信息: 我们开始 typescript 作为一个插件,用于创建 GraphQL 模式的精确表示。 然后,typescript-operations 获取操作和片段(从架构中选择特定字段和数据)并生成代码,该代码从 typescript 插件生成的类型中获取相同的字段和数据字段。

    我们看到一些开发人员更喜欢更简洁的代码,因此您可以使用preResolveTypes: true 来避免使用Pick,而只需就地使用原始类型。 您也可以使用onlyOperationTypes: true 来告诉代码生成器避免生成不需要的类型。

    【讨论】:

    • 感谢您的回答@dotan!一定会尽快尝试并提供反馈,似乎对我们真的有用。
    猜你喜欢
    • 2019-11-12
    • 2020-12-21
    • 1970-01-01
    • 2020-07-01
    • 2020-03-03
    • 2022-06-25
    • 2016-12-26
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多