【问题标题】:Generate the correct type instead of a union in GraphQL codegen在 GraphQL codegen 中生成正确的类型而不是联合
【发布时间】:2022-07-31 10:21:54
【问题描述】:

我正在尝试将生成所有类型的设置迁移到与服务器所具有的完全相同的设置,该设置仅基于我们编写的文档节点。

我目前在.graphqlrc.js有这个配置

/** @type {import('graphql-config').IGraphQLConfig} */
const graphqlConfig = {
  schema: process.env.NEXT_PUBLIC_API_URL,
  documents: './src/graphql/**/*.ts',
  extensions: {
    codegen: {
      hooks: {
        afterAllFileWrite: ['prettier --write'],
      },
      generates: {
        './src/__generated__/graphql.ts': {
          plugins: [
            'typescript',
            'typescript-operations',
            {
              add: {
                content: '/* eslint-disable */',
              },
            },
          ],
          config: {
            disableDescriptions: true,
          },
        },
        './src/__generated__/introspection-result.ts': {
          plugins: ['fragment-matcher'],
          config: {
            useExplicitTyping: true,
          },
        },
      },
    },
  },
}

这会产生类似下面的东西

export type QueryName = {
  __typename?: 'Query'
  resource?:
    | { __typename?: 'A' }
    | { __typename?: 'B' }
    | {
        __typename?: 'C'
        id: string
        prop1: any
        prop2: any
      }
}

这并不是我所期望的。我期待类似的东西

export type QueryName = {
  __typename?: 'Query'
  resource?: {
        __typename?: 'C'
        id: string
        prop1: any
        prop2: any
  }
}

因为我只查询C。当前生成的类型会影响很多代码,而如果我可以输出我想要实现的内容,我们只需要更改类型即可。

我尝试过使用here 找到的配置,但找不到解决方案。请让我知道这是否可行,或者我可以看看解决这个问题的方法。

提前致谢!

【问题讨论】:

    标签: typescript graphql codegen graphql-codegen


    【解决方案1】:

    我最终为此使用了tiny-invariant 包。考虑ff代码

    const {data} = useUserQuery({variables: {id}});
    
    // more codes here...
    
    invariant(data.user.__typename === "User");
    
    // now we should get the type that we want here
    

    【讨论】:

      【解决方案2】:

      你也可以

      if (data.user.__typename === "User") { ... };
      

      以确保它引用您需要的联合中的类型

      【讨论】:

        猜你喜欢
        • 2020-12-21
        • 2019-11-12
        • 2022-01-22
        • 2021-02-09
        • 2020-02-29
        • 2020-03-22
        • 2021-10-10
        • 2021-12-29
        • 2023-03-03
        相关资源
        最近更新 更多