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

NestJS中InputType与ObjectType的区别是什么?

ObjectType 和 InputType 在NestJS GraphQL中的核心区别

核心用途差异

  • ObjectType:专门定义GraphQL的返回数据结构,对应GraphQL Schema里的type关键字。它是服务端返回给客户端的数据模型,通常和Resolver配合,作为查询(Query)或变更(Mutation)的返回值。
  • InputType:专门定义GraphQL的输入参数结构,对应GraphQL Schema里的input关键字。它是客户端传递给服务端的请求数据模型,主要用于Mutation的参数、嵌套输入场景中。

定义与使用示例

ObjectType 示例

import { ObjectType, Field } from '@nestjs/graphql';

@ObjectType()
export class User {
  @Field()
  id: string;

  @Field()
  username: string;

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

生成的GraphQL Schema:

type User {
  id: String!
  username: String!
  email: String
}

在Resolver中作为返回值使用:

@Query(() => User)
async getUser(@Args('id') id: string) {
  return this.userService.findById(id);
}

InputType 示例

import { InputType, Field } from '@nestjs/graphql';

@InputType()
export class CreateUserInput {
  @Field()
  username: string;

  @Field()
  password: string;

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

生成的GraphQL Schema:

input CreateUserInput {
  username: String!
  password: String!
  email: String
}

在Mutation中作为参数使用:

@Mutation(() => User)
async createUser(@Args('input') input: CreateUserInput) {
  return this.userService.create(input);
}

GraphQL规范层面的限制

  • ObjectType的字段可以嵌套其他ObjectType、枚举类型,甚至可以关联Resolver的动态字段(比如嵌套查询),但绝对不能作为输入参数的类型。
  • InputType的字段只能是标量类型、枚举类型或其他InputType,不能嵌套ObjectType,也无法定义Resolver相关的动态字段——因为输入类型是客户端传递的静态数据结构,不需要服务端动态解析。

内容的提问来源于stack exchange,提问作者Léonard Henriquez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:55:20