musement / types-generator

3 stars 1 forks source link

Support Swagger's "additionalProperties" keyword for object with dynamic keys #22

Open GabriMcNab opened 2 years ago

GabriMcNab commented 2 years ago

In an OpenAPI document, when an object has some dynamic keys, it's declared like so:

someObject:
  type: object
  additionalProperties:
    type: string

Currently, the additionalProperties keyword is ignored, and the Typescript type is generated in this way:

someObject: {}

If you are using typescript-eslint > v5.0.0, this will raise an error, because the empty object literal syntax is banned, as it is considered unsafe. Instead we should use:

someObject: Record<string, string>

In addition to the example shown above, there are other use cases for additionalProperties:

someObject:
  type: object
  additionalProperties: true

If the dictionary values can be of any type (aka free-form object) --> Record<string, unknown>

someObject:
  type: object
  additionalProperties:
    $ref: '#/components/schemas/Message'

Instead of using an inline schema, additionalProperties can $ref another schema

someObject:
  type: object
  properties:
    default:
      type: string
  required:
    - default
  additionalProperties:
    type: string

When a dictionary has some fixed properties, and some dynamic ones.

BenisonSam commented 7 months ago

I am also arrived at this. Is there any solution for this?