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

NestJs Swagger:如何为动态类的索引签名定义ApiProperty类型

解决方案

你需要给@ApiProperty的type参数传入返回Record类型的工厂函数,具体写法如下:

import { ApiProperty } from '@nestjs/swagger';
import { DocumentStep } from './document-step.dto'; // 替换为你实际的DocumentStep导入路径

export class DocumentsSteps {
    @ApiProperty({ type: () => Record<string, DocumentStep> })
    [type: string]: DocumentStep;
}

说明

  • Record<string, DocumentStep>是TypeScript内置工具类型,刚好匹配「键为字符串、值为DocumentStep类型」的索引签名结构,@nestjs/swagger可以正确识别该类型生成对应的OpenAPI Schema
  • 请确保DocumentStep类本身已经通过@ApiProperty声明了内部所有属性,或者已经用@ApiExtraModels(DocumentStep)注册到Swagger中,避免生成Schema时丢失属性定义
  • 如果需要配置接口示例,可以在@ApiProperty的参数中新增example字段,传入符合结构的示例值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:36:02