首页 > 解决方案 > 如何使`[key: string]: string`出现在NestJS Swagger生成中

问题描述

我有以下代表响应的类:

class SomeResponse {
  property1?: string;
  [key: string]: string
}

我想使用 nest-cli 为这个响应生成正确的 swagger 文档。它适用于我的所有其他simpler属性,即property1在招摇中正确显示。我也尝试过直接注释:

class SomeResponse {
  property1?: string;
  @ApiProperty()
  [key: string]: string
}

但这是不允许的,因为这给出了:error TS1206: Decorators are not valid here.

有没有办法手动注释或使用 nest-cli 结构进行注释[key: string]: string

标签: typescriptswaggernestjs

解决方案


不幸的是,装饰器似乎不能附加到索引签名上。您也可以使用additionalProperties(参见此处),但它会生成一个嵌套对象。

class SomeResponse {
  @ApiProperty({ type: 'object', additionalProperties: { type: 'string' } })
  data: Record<string, string>;
}

这将被提取如下。

{
  "data": {
    "additionalProp1": "string",
    "additionalProp2": "string",
    "additionalProp3": "string"
  }
}

推荐阅读