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 generates schema that accepts too much #1492

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

Comments

@mvanniekerkSQ
Copy link
Contributor

Generating a schema for a union type creates a schema that accepts anything if the value for the discriminator is not one of the values in the union. For example:

Typescript types:

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

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

export type B = {
    type: "B",
    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": "B"
              }
            }
          },
          "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": "B"
        },
        "b": {
          "type": "string"
        }
      },
      "required": [
        "type",
        "b"
      ],
      "additionalProperties": false
    }
  }
}

Currently the schema would validate against for example this JSON while it should not be accepted:

{
	"type": "C",
	"c": "this is a string"
}

Note that the type Union does not require the discriminator value to be one of the constants defined in the type and expected by the if keyword. This problem can be fixed by requiring the Union type to have a type that is either "a" or "b" like so:

  "properties": {
    "type": {
      "enum": ["a", "b"]
    }
  },
@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