Angular Apollo Codegen返回匿名对象智能提示问题求助
问题分析与解决方案
你遇到的核心问题是GraphQL Codegen已生成Animal类型,但Apollo Client查询结果的类型推断仍为匿名对象,而非预期的Animal[]。以下是具体原因排查和解决步骤:
1. 先确认Schema与查询的类型关联
首先检查你的GraphQL Schema中是否明确定义了Animal类型,且Query的animals字段返回类型为[Animal!]!:
# schema.graphql type Animal { id: ID! name: String! latinName: String! created: DateTime! changed: DateTime! changedBy: String! } type Query { animals: [Animal!]! }
如果Schema中animals字段返回的是匿名结构(而非关联到Animal类型),Codegen会生成匿名对象类型而非复用Animal。
2. 调整Codegen配置确保类型复用
修改codegen.ts配置,确保启用正确的插件并配置类型复用规则:
import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { schema: './src/graphql/schema.graphql', // 你的Schema路径 documents: ['./src/**/*.graphql'], // 你的查询文件路径 generates: { './src/generated/graphql.ts': { plugins: [ 'typescript', 'typescript-operations', 'typescript-apollo-angular' ], config: { namingConvention: { typeNames: 'pascal-case', // 确保类型名大驼峰(如Animal) enumValues: 'upper-case' }, avoidOptionals: true, // 禁用可选类型匹配Schema的非空约束 maybeValue: 'T', // 处理nullable类型为T而非T | null scalars: { // 配置自定义标量映射,比如DateTime对应Date DateTime: 'Date' } } } } }; export default config;
重新运行Codegen命令(如npm run generate),检查生成的graphql.ts文件,确认AnimalsQuery类型中的animals字段为Animal[]:
export type AnimalsQuery = { __typename?: 'Query'; animals: Array<Animal>; }; export type Animal = { __typename?: 'Animal'; id: string; name: string; latinName: string; created: Date; changed: Date; changedBy: string; };
3. 组件中正确使用生成的类型
方式1:使用生成的GQL服务
Codegen会为每个查询生成对应的GQL服务类(如AnimalsGQL),直接使用它即可获得正确的类型推断:
import { Component, OnInit } from '@angular/core'; import { AnimalsGQL } from './generated/graphql'; @Component({ selector: 'app-animal-list', templateUrl: './animal-list.component.html' }) export class AnimalListComponent implements OnInit { animals: Animal[] = []; constructor(private animalsGQL: AnimalsGQL) {} ngOnInit(): void { this.animalsGQL.watch().valueChanges.subscribe(({ data }) => { // 此处data.animals会自动推断为Animal[] this.animals = data.animals; }); } }
方式2:手动调用Apollo Client时指定泛型
如果手动调用apollo.query,必须显式指定泛型类型以触发正确的类型推断:
// 错误写法:无泛型,返回匿名对象类型 this.apollo.query({ query: AnimalsDocument }).subscribe(res => { // res.data为匿名类型 }); // 正确写法:指定AnimalsQuery泛型 this.apollo.query<AnimalsQuery>({ query: AnimalsDocument }).subscribe(res => { // res.data.animals为Animal[] this.animals = res.data.animals; });
4. 检查依赖版本兼容性
确保@graphql-codegen系列包与apollo-angular、@apollo/client版本兼容,避免因版本不匹配导致的类型生成异常。推荐的依赖版本参考:
{ "dependencies": { "@apollo/client": "^3.8.0", "apollo-angular": "^4.0.0", "graphql": "^16.8.0" }, "devDependencies": { "@graphql-codegen/cli": "^5.0.0", "@graphql-codegen/typescript": "^4.0.0", "@graphql-codegen/typescript-operations": "^4.0.0", "@graphql-codegen/typescript-apollo-angular": "^4.0.0" } }
内容的提问来源于stack exchange,提问作者baouss
相关产品推荐
相关产品推荐

