gpt4 book ai didi

typescript - 在 GraphQL codegen 中生成正确的类型而不是联合

转载 作者:行者123 更新时间:2023-12-05 04:29:46 25 4
gpt4 key购买 nike

我正在尝试将生成所有类型的设置迁移到仅基于我们编写的文档节点的服务器中。

我目前在 .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但找不到解决办法。请让我知道这是否可行,或者我是否可以考虑解决此问题。

提前致谢!

最佳答案

我最终使用了 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

关于typescript - 在 GraphQL codegen 中生成正确的类型而不是联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72230166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com