You need to enable JavaScript to run this app. 如何使用Nestjs OpenApi对返回Record<K,V>类型的接口进行文档标注?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Nestjs OpenApi对返回Record<K,V>类型的接口进行文档标注?

报错原因

Record<KeyEnum, ValueClass>是TypeScript专属的编译期类型,运行时会被完全抹除,不存在对应的JavaScript值。而@ApiOkResponse的type字段要求传入运行时真实存在的构造函数/类,因此直接传入Record类型会触发类型错误。

解决方案

通过自定义schema配置替代type字段即可实现Record结构的文档标注,具体实现如下:

  1. 先给ValueClass的所有字段添加@ApiProperty注解,确保Swagger可识别该类的结构:
import { ApiProperty } from '@nestjs/swagger';

export class ValueClass {
  // 示例字段,按实际业务替换
  @ApiProperty()
  name: string;

  @ApiProperty()
  count: number;
}
  1. 调整接口的@ApiOkResponse配置,使用schema字段声明Record结构:
import { ApiOkResponse, getSchemaPath, ApiExtraModels } from '@nestjs/swagger';

// 如果ValueClass未被Swagger自动扫描到,需要在控制器类上加该注解手动注册
@ApiExtraModels(ValueClass)
@Controller()
export class YourController {
  @Get('my/endpoint')
  @ApiOkResponse({
    schema: {
      type: 'object',
      // 声明对象所有value的结构为ValueClass
      additionalProperties: { $ref: getSchemaPath(ValueClass) },
      // 可选:如果需要在文档中明确列出所有枚举key,添加以下配置
      properties: Object.values(KeyEnum).reduce((acc, key) => {
        acc[String(key)] = { $ref: getSchemaPath(ValueClass) };
        return acc;
      }, {} as Record<string, unknown>)
    },
    description: 'some description',
  })
  public async myEndpoint(): Promise<Record<KeyEnum, ValueClass>> {
    return this.myService.method();
  }
}
注意事项
  • 如果你的KeyEnum是数字枚举,必须通过String(key)转成字符串格式,因为JSON对象的key仅支持字符串类型。
  • 如果不需要在文档中明确展示所有可选key,删除properties配置项即可,仅保留additionalProperties就能说明该接口返回键值对结构。

内容的提问来源于stack exchange,提问作者Gerson Ferreira Junior

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 20:54:03