How to make `[key: string]: string` appear in NestJS Swagger generation

Viewed 675

I have the following class that represents a response:

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

I want to use the nest-cli to generate the correct swagger documentation for this response. It works for all my other simpler properties i.e. property1 shows correctly in the swagger. I also tried annotating directly with:

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

but this is not allowed, as this gives: error TS1206: Decorators are not valid here.

Is there a way to annotate manually or with the nest-cli constructions like [key: string]: string?

1 Answers

Unfortunately, it seems decorators cannot be attached to index signatures. You can alternatively use additionalProperties (see here) but it will make a nested object.

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

This will be extracted as the following.

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