You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apollo Client使用GraphQL联合类型返回空对象问题求助

问题描述

使用GraphQL联合类型查询,示例查询如下:

person {
  ... on jedi{
    id
    lightsaber
  }
  ... on mandalorian{
    id
    beskar
  }
}

通过fetch()请求可正常返回:

[{id:232, lightsaber:'green'},{id:242, beskar: 'old'}]

但使用Apollo Client的useQuery时,返回的person对象为[{},{}]。已尝试在客户端配置联合类型:

const client = new ApolloClient({
  link: concat(authMiddleware, httpLink),
  cache: new InMemoryCache({
    addTypename: false,
    possibleTypes:{PersonUnion:['jedi','mandalorian']}
  }),
})

useQuery代码:const {data:QueryData} = useQuery<PersonQuery>(GET_PERSON),问题仍未解决。

解决方案

核心原因

Apollo Client的InMemoryCache依赖__typename字段识别联合类型的具体类型,进而正确解析数据。你设置了addTypename: false,导致客户端无法从响应中获取类型标识,无法匹配possibleTypes配置,最终返回空对象。

修复步骤

  1. 移除addTypename: false配置
    让Apollo Client自动为查询添加__typename字段,并确保后端响应包含对应类型的__typename(比如jedi类型响应带__typename: "jedi",mandalorian类型带__typename: "mandalorian")。

  2. 保留正确的possibleTypes配置
    确保PersonUnion与具体类型映射正确,修正后的客户端配置如下:

    const client = new ApolloClient({
      link: concat(authMiddleware, httpLink),
      cache: new InMemoryCache({
        possibleTypes: {
          PersonUnion: ['jedi', 'mandalorian']
        }
      }),
    })
    
  3. 验证查询与响应

    • 开启addTypename后,Apollo会自动在查询的每个选择集中添加__typename,无需手动编写。
    • 确认后端返回的每个对象都包含__typename字段,例如:
      [
        {id:232, lightsaber:'green', __typename: "jedi"},
        {id:242, beskar: 'old', __typename: "mandalorian"}
      ]
      
  4. 检查TypeScript类型定义
    确保PersonQuery类型正确包含联合类型的字段,示例:

    type Jedi = {
      __typename: "jedi";
      id: string;
      lightsaber: string;
    };
    
    type Mandalorian = {
      __typename: "mandalorian";
      id: string;
      beskar: string;
    };
    
    type PersonUnion = Jedi | Mandalorian;
    
    type PersonQuery = {
      person: PersonUnion[];
    };
    

内容的提问来源于stack exchange,提问作者Gowthaman Ganesan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 23:11:01