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

TypeGraphQL中如何定义对象类型字段?解决类型识别报错

解决TypeGraphQL中合并字段为对象类型的报错问题

要实现把producedByUserName和producedByUserEmail合并为producedBy对象字段的需求,你需要给这个对象定义明确的TypeGraphQL类型——因为TypeGraphQL无法自动识别匿名Object或Record类型,这就是你报错的核心原因。具体解决步骤如下:

1. 定义对应的对象类型

先创建一个新的@ObjectType()类,用来描述producedBy的结构:

import { ObjectType, Field } from "type-graphql";

@ObjectType()
class Producer {
  @Field({ nullable: true })
  name?: string;

  @Field({ nullable: true })
  email?: string;
}

2. 修改Game类的实现

将producedBy方法的返回类型指定为刚才定义的Producer,并更新@Field的类型参数:

import { ObjectType, Field, Int } from "type-graphql";

@ObjectType()
export class Game {
  @Field(() => Int)
  id: number;

  // 保留这两个属性但不标记为@Field,仅作为内部数据使用
  producedByUserName?: string;
  producedByUserEmail?: string;

  @Field(() => Producer, { name: 'producedBy', nullable: true })
  producedBy() {
    return {
      name: this.producedByUserName,
      email: this.producedByUserEmail,
    };
  }
}

报错原因补充

GraphQL要求所有输出类型必须是明确的命名类型,你之前用Object或Record<string, string>作为类型时,TypeGraphQL无法将这些泛型/匿名类型映射为GraphQL能识别的输出结构,因此抛出CannotDetermineGraphQLTypeError错误。通过显式定义Producer类型,就能让TypeGraphQL正确生成对应的GraphQL Schema。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:25:04