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
相关产品推荐
相关产品推荐

