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

React(Next.js)+TypeScript中去除GraphQL返回数据的__typename字段

移除GraphQL返回结果中的__typename字段

Apollo Client默认会为GraphQL查询结果添加__typename字段用于缓存管理,以下是几种移除该字段的实用方案:

方法一:全局关闭自动添加__typename

在创建InMemoryCache时关闭addTypename选项,可全局禁用自动添加__typename:

修改你的Apollo Client配置文件:

import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://countries.trevorblades.com/graphql',
  cache: new InMemoryCache({
    addTypename: false, // 关闭自动添加__typename
  }),
});

export default client;

注意:此操作会影响Apollo的缓存识别逻辑,若项目依赖缓存功能需谨慎使用。

方法二:组件内手动过滤字段

针对单个组件的查询结果,手动移除__typename字段,不影响全局配置:

import { useQuery } from '@apollo/client';
import { gql } from '@apollo/client';

const GET_ITEMS = gql`
query Query  {
    countries {
        code
        name
        emoji
      }
  }`;

// 递归移除对象/数组中的__typename字段
const removeTypename = (obj: any): any => {
  if (Array.isArray(obj)) {
    return obj.map(item => removeTypename(item));
  } else if (obj !== null && typeof obj === 'object') {
    const { __typename, ...rest } = obj;
    Object.keys(rest).forEach(key => {
      rest[key] = removeTypename(rest[key]);
    });
    return rest;
  }
  return obj;
};

function ItemList() {
  const { loading, error, data } = useQuery(GET_ITEMS);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;  

  // 处理数据,移除__typename
  const processedData = removeTypename(data);

  return (
    <div>
      {JSON.stringify(processedData)}
    </div> 
  );
}

export default ItemList;

方法三:通过Apollo Link全局拦截移除

自定义Apollo Link在响应返回客户端前全局移除__typename,既保留缓存功能又统一处理所有查询:

首先安装依赖(若未安装):

npm install apollo-link

修改Apollo Client配置:

import { ApolloClient, InMemoryCache, ApolloLink, from } from '@apollo/client';
import { HttpLink } from '@apollo/client/link/http';

// 自定义Link:拦截响应并移除__typename
const removeTypenameLink = new ApolloLink((operation, forward) => {
  return forward(operation).map(response => {
    const removeTypename = (obj: any): any => {
      if (Array.isArray(obj)) {
        return obj.map(item => removeTypename(item));
      } else if (obj !== null && typeof obj === 'object') {
        const { __typename, ...rest } = obj;
        Object.keys(rest).forEach(key => {
          rest[key] = removeTypename(rest[key]);
        });
        return rest;
      }
      return obj;
    };

    if (response.data) {
      response.data = removeTypename(response.data);
    }
    return response;
  });
});

const httpLink = new HttpLink({
  uri: 'https://countries.trevorblades.com/graphql',
});

const client = new ApolloClient({
  link: from([removeTypenameLink, httpLink]),
  cache: new InMemoryCache(),
});

export default client;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 06:42:41