Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using discriminator annotation for union types with not unique discriminator generates schema that is logically inconsistent #1494

Closed
mvanniekerkSQ opened this issue Dec 9, 2022 · 1 comment · Fixed by #1493

Comments

@mvanniekerkSQ
Copy link
Contributor

Using a discriminator annotation for union types with a non-unique discriminator generates a schema that is logically inconsistent.

For example:

/**
 * @discriminator type
 */
export type Union
    = A | B;

export type A = {
    type: "A",
    a: string,
}

export type B = {
    type: "A",
    b: string,
}

Gives the following output:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$ref": "#/definitions/Union",
  "definitions": {
    "Union": {
      "allOf": [
        {
          "if": {
            "properties": {
              "type": {
                "type": "string",
                "const": "A"
              }
            }
          },
          "then": {
            "$ref": "#/definitions/A"
          }
        },
        {
          "if": {
            "properties": {
              "type": {
                "type": "string",
                "const": "A"
              }
            }
          },
          "then": {
            "$ref": "#/definitions/B"
          }
        }
      ]
    },
    "A": {
      "type": "object",
      "properties": {
        "type": {
          "type": "string",
          "const": "A"
        },
        "a": {
          "type": "string"
        }
      },
      "required": [
        "type",
        "a"
      ],
      "additionalProperties": false
    },
    "B": {
      "type": "object",
      "properties": {
        "type": {
          "type": "string",
          "const": "A"
        },
        "b": {
          "type": "string"
        }
      },
      "required": [
        "type",
        "b"
      ],
      "additionalProperties": false
    }
  }
}

In this schema, having type 'A' requires both schema A and B to be valid. However, they are mutually exclusive. A requires fields type and a and no additional properties. B requires fields type and b and no additional properties. So the schema cannot be satisfied.

The simplest solution for this is requiring that each discriminator key is unique. This issue is related to #1492 .

@github-actions
Copy link

github-actions bot commented Dec 9, 2022

🚀 Issue was released in v1.2.0-next.4 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
1 participant