ts-json-schema-generator icon indicating copy to clipboard operation
ts-json-schema-generator copied to clipboard

Enhancement: support polymorphic arrays

Open dselman opened this issue 1 year ago • 0 comments

Command: npx ts-json-schema-generator --path '*.ts' --type Zoo

Input:

export interface Animal {
    name: string;
}

export interface Dog extends Animal {
    breed: string;
}

export interface Cat extends Animal {
    color: string;
}

export class Zoo {
    animals:Array<Animal>[];
}

Output:

{
  "$ref": "#/definitions/Zoo",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "Animal": {
      "additionalProperties": false,
      "properties": {
        "name": {
          "type": "string"
        }
      },
      "required": [
        "name"
      ],
      "type": "object"
    },
    "Zoo": {
      "additionalProperties": false,
      "properties": {
        "animals": {
          "items": {
            "items": {
              "$ref": "#/definitions/Animal"
            },
            "type": "array"
          },
          "type": "array"
        }
      },
      "required": [
        "animals"
      ],
      "type": "object"
    }
  }
}

In this case I think it would be useful if the definition of items for the animals array was:

"items": {
            "anyOf": [
              {
                "$ref": "#/definitions/Cat"
              },
              {
                "$ref": "#/definitions/Dog"
              },
              {
                "$ref": "#/definitions/Animal"
              }
            ]
          }

And the Cat and Dog definitions were included in the schema.

dselman avatar Nov 23 '23 14:11 dselman