bcherny/json-schema-to-typescript

required ignored for properties referencing definitions with allOf

Open

#395 opened on May 19, 2021

View on GitHub
 (11 comments) (4 reactions) (0 assignees)TypeScript (449 forks)github user discovery
buggood first issuehelp wanted

Repository metrics

Stars
 (3,302 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

Hi,

I've noticed what seems like a bug with the generated types when the required keyword is used in a property which references a definition using allOf

Here's an example schema:

{
  "title": "Example Schema",
  "type": "object",
  "properties": {
    "reference": {
      "allOf": [{ "$ref": "#/definitions/defined" }],
      "required": ["subproperty"]
    }
  },
  "definitions": {
    "defined": {
      "type": "object",
      "properties": {
        "subproperty": {
          "type": "integer"
        }
      }
    }
  },

  "additionalProperties": false
}

and the generated typings

export interface ExampleSchema {
  reference?: Defined;
}
export interface Defined {
  subproperty?: number;
  [k: string]: unknown;
}

I understand that the interface Defined is probably just pulled straight from the definitions section which is why the subproperty key is optional, but I would expect that the generated types would know that the Defined interface being used by ExampleSchema has subproperty as mandatory.

If you explore this in a json schema validator you will see that given the example schema above, this object:

{
   "reference": {
      "foo": "bar"
    }
}

is invalid since Required properties are missing from object: subproperty.

but with the current json-schema-to-typescript implementation,

const thing:ExampleSchema = {
   "reference": {
      "foo": "bar"
    }
}

is valid

Contributor guide